Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting array of objects by property

I have this collection from DataBase:

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 }]

I need to sort this items by TypeId increasing.

Like that:

var itemsSorted = [{ 'Name':'Michael', 'TypeId':1 }
        { 'Name':'Max', 'TypeId':1 }
        { 'Name':'Andre', 'TypeId':1 }
        { 'Name':'Ptro', 'TypeId':1 }
        { 'Name':'Helga', 'TypeId':1 }
        { 'Name':'Georg', 'TypeId':2 }
        { 'Name':'Mitchell', 'TypeId':2 }
        { 'Name':'Marta', 'TypeId':2 }]
        { 'Name':'Seruin', 'TypeId':2 }
        { 'Name':'Greg', 'TypeId':3 }
        { 'Name':'Ann', 'TypeId':3 }

Is there any built in function in JavaScript that can sort array of objects by property?

like image 968
Michael Avatar asked Apr 16 '16 18:04

Michael


People also ask

Can we sort array of objects?

Sorting array of objectsArrays of objects can be sorted by comparing the value of one of their properties.

How do you sort an object by property in powershell?

If you want to sort by multiple properties, separate the properties by commas. The Get-ChildItem cmdlet gets the files from the directory specified by the Path parameter. The objects are sent down the pipeline to the Sort-Object cmdlet.


2 Answers

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.

like image 167
Pankaj Parkar Avatar answered Oct 05 '22 17:10

Pankaj Parkar


In a template:

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

In a controller/service:

vm.sortedItems = $filter('orderBy')(items, 'TypeId');
like image 44
GG. Avatar answered Oct 05 '22 19:10

GG.