Javascript Object Array sort by property

Hi Guys,

I thought this would be a nice share just in case you are looking for information on how to sort Javascript Object arrays.

As you may be aware that Javascript comes with a handy function called sort(function)

You can read more about it here

http://www.w3schools.com/jsref/jsref_sort.asp

There are couple of things that this method is capable of. Either you can trust default sort or you can create your own function to sort.

Let me show you couple of example to elaborate more on what I am saying.

Alright consider this array

  1. var myArray = ['b','c','z','blah',0];

Now if you use sort() method on the above array as shown below

  1. myArray.sort();

Result will be

  1. [0, "b", "blah", "c", "z"]

which is cool.

What if you need to sort your array of object based on a property of an object. Well surely this approach wont work in that scenario. So what will work. Lets find out

Consider the Object array as shown below

  1. var myObjArray = [
  2. {Name:'Jas',Score: 65},
  3. {Name:'Tim',Score: 55},
  4. {Name:'Alex',Score: 75},
  5. {Name:'David',Score: 74},
  6. {Name:'Jason',Score: 92},
  7. {Name:'James',Score: 52}
  8. ];

Lets say I want to sort the above array in ascending order based on property value of Score

Below is how thats done

 

  1. myObjArray.sort(function(objA,objB) {
  2. return objA.Score - objB.Score;
  3. })

Notice that I am using operator (-) you can also use (>) to get the same output that is Ascending Sort.

Now if you try to output myObjArray to Javascript console then you will get below output

  1. [
  2. Object{
  3. Name: "James"
  4. Score: 52}
  5. ,
  6. Object{
  7. Name: "Tim"
  8. Score: 55}
  9. ,
  10. Object{
  11. Name: "Jas"
  12. Score: 65}
  13. ,
  14. Object{
  15. Name: "David"
  16. Score: 74}
  17. ,
  18. Object{
  19. Name: "Alex"
  20. Score: 75}
  21. ,
  22. Object{
  23. Name: "Jason"
  24. Score: 92}
  25. ]

 

Advertisement

 

If you want to sort this Object array based on Descending value of Score then either change the operator to objA.Score < objB.Score as shown below

  1. myObjArray.sort(function(objA,objB) {
  2. return objA.Score < objB.Score;
  3. })

I am not doing to go in details how sort works but the idea was to show how to utilize Javascript’s internal functions to sort object arrays.

I hope this helps

Cheers,

 

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Speak Your Mind

*

CommentLuv badge