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
var myArray = ['b','c','z','blah',0];
Now if you use sort() method on the above array as shown below
myArray.sort();
Result will be
[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
var myObjArray = [ {Name:'Jas',Score: 65}, {Name:'Tim',Score: 55}, {Name:'Alex',Score: 75}, {Name:'David',Score: 74}, {Name:'Jason',Score: 92}, {Name:'James',Score: 52} ];
Lets say I want to sort the above array in ascending order based on property value of Score
Below is how thats done
myObjArray.sort(function(objA,objB) { return objA.Score - objB.Score; })
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
[ Object{ Name: "James" Score: 52} , Object{ Name: "Tim" Score: 55} , Object{ Name: "Jas" Score: 65} , Object{ Name: "David" Score: 74} , Object{ Name: "Alex" Score: 75} , Object{ Name: "Jason" Score: 92} ]
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
myObjArray.sort(function(objA,objB) { return objA.Score < objB.Score; })
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,





JC WordPress Coupon Revealer Plugin Pro License
Australian Street Names with City, State and Display Names only, Single Server License
Recent Comments