josh asked this 3 years ago

Sort an array of objects (JSON) using JavaScript

There is an array of objects with a string attribute called name and a number attribute called age.

 arr = [ {name: "abba", age: 23}, {name: "lovely", age: 23}, {name: "vincent", age: 5}, {name: "jam", age: 100}, {name: "cherry", age: 8}, {name: "rags", age: 70} ]

How to sort this in the order of age attribute?


Best Answer by dig_abacus
4 likes

Javascript sort() method accepts a comparison function as argument. The comparison logic (sort order) can be defined inside this function.  

For ascending order sort,

arr.sort ( function (a, b)  { return (a.age - b.age); } );

For descending order sort,

arr.sort ( function (a, b) { return (b.age - a.age); } );

Without the comparison function, the method sorts the array according to each character's Unicode code point value and hence is not reliable.