In this article I will discuss about how to sort array of objects by property or key value. Consider the following array of objects:
var obj = [
{ name: 'Ravi', age: 20 },
{ name: 'Ajay', age: 55 },
{ name: 'Henry', age: 15 }
];
Suppose you want to sort the array of objects by key name
or age
value as shown below.
// Sorted by name value
[
{ name: 'Ajay', age: 55 },
{ name: 'Henry', age: 15 },
{ name: 'Ravi', age: 20 }
];
// Sorted by age value
[
{ name: 'Henry', age: 15 },
{ name: 'Ravi', age: 20 },
{ name: 'Ajay', age: 55 }
];
Let’s define a function say, sortByKey(array, string, boolean)
for this purpose. The function will accepts three arguments – array of object to be sorted, string property name by the value of which it should be sorted and the order in which the value should be sorted.
function sortByKey (arrayOfObjects, prop, isAsc) {
return arrayOfObjects.sort(function(a, b){
return (a[prop] < b[prop] ? -1 : 1) * (isAsc ? 1 : -1)
});
}
The third argument isAsc accepts boolean true
or false
. Pass true for ascending order, false for descending order. Checkout the following examples:
var obj = [
{ name: 'Ravi', age: 20 },
{ name: 'Ajay', age: 55 },
{ name: 'Henry', age: 15 }
];
// Sort by name in ascending order
var sorted1 = sortByKey(obj, 'name', true);
console.log(sorted1);
// Output:
[{"name":"Ajay","age":55},{"name":"Henry","age":15},{"name":"Ravi","age":20}]
// Sort by name in descending order
sorted2 = sortByKey(obj, 'name', false);
console.log(sorted2);
// Output:
[{"name":"Ravi","age":20},{"name":"Henry","age":15},{"name":"Ajay","age":55}]
// Sort by age in ascending order
sorted3 = sortByKey(obj, 'age', true);
console.log(sorted3);
// Output:
[{"name":"Henry","age":15},{"name":"Ravi","age":20},{"name":"Ajay","age":55}]