Sorting array of objects by property

前端 未结 4 1784
梦毁少年i
梦毁少年i 2021-02-14 09:48

I have this collection from DataBase:

var items = [{ \'Name\':\'Michael\', \'TypeId\':1 }
        { \'Name\':\'Max\', \'TypeId\':1 }
        { \'Name\':\'Andre\'         


        
相关标签:
4条回答
  • 2021-02-14 10:40

    You can use js sort function & ternary operator

    var items = [{ 'Name':'Michael', 'TypeId':1 },
                { 'Name':'Max', 'TypeId':1 },
                { 'Name':'Andre', 'TypeId':1 },
                { 'Name':'Georg', 'TypeId':2 },
                { 'Name':'Greg', 'TypeId':3 },
                { 'Name':'Mitchell', 'TypeId':2 },
                { 'Name':'Ptro', 'TypeId':1 },
                { 'Name':'Helga', 'TypeId':1 },
                { 'Name':'Seruin', 'TypeId':2 },
                { 'Name':'Ann', 'TypeId':3 },
                { 'Name':'Marta', 'TypeId':2 }]
        var sortedArray = items.sort(function(a,b){
         return a.TypeId >b.TypeId?1:a.TypeId <b.TypeId?-1:0
        })
        console.log(sortedArray);
    

    JSFIDDLE Example

    0 讨论(0)
  • 2021-02-14 10:40

    You can use Array.prototype.sort:

    var items = [{ 'Name':'Michael', 'TypeId':1 },
            { 'Name':'Max', 'TypeId':1 },
            { 'Name':'Andre', 'TypeId':1 },
            { 'Name':'Georg', 'TypeId':2 },
            { 'Name':'Greg', 'TypeId':3 },
            { 'Name':'Mitchell', 'TypeId':2 },
            { 'Name':'Ptro', 'TypeId':1 },
            { 'Name':'Helga', 'TypeId':1 },
            { 'Name':'Seruin', 'TypeId':2 },
            { 'Name':'Ann', 'TypeId':3 },
            { 'Name':'Marta', 'TypeId':2 }];
    
    
    items.sort(function(a, b) { return a.TypeId - b.TypeId; })
    
    console.table(items);
    
    document.getElementById('demo').innerHTML = JSON.stringify(items, null, 4);
    <pre id="demo"></pre>

    0 讨论(0)
  • 2021-02-14 10:47

    You could use orderBy filter.

    var itemsSorted  = $filter('orderBy')(items, 'TypeId')
    

    On View

    ng-repeat="item in items | orderBy: 'TypeId'"
    

    By default filters are ascending(explicit would be +TypeId), you could use -TypeId to make it descending.


    Additional Stuff

    If you wanted to sort by multiple properties then do use array instead of string like ['TypeId', 'Name']

    ng-repeat="item in items | orderBy: ['TypeId', 'Name']"
    

    There is big performance benefit you get when you do manual filtering inside controller. where as filtering on view is slower as it evaluates ng-repeat express and bindings each time when digest cycle fire. Generally you won't see any performance hit in small collection, but in bigger collection you will see filtering on view will work slow.

    0 讨论(0)
  • 2021-02-14 10:47

    In a template:

    <li ng-repeat="item in items | orderBy:'TypeId'">...</li>
    

    In a controller/service:

    vm.sortedItems = $filter('orderBy')(items, 'TypeId');
    
    0 讨论(0)
提交回复
热议问题