How to Sort an Array of Objects by Property Values in JavaScript
Topic: JavaScript / jQueryPrev|Next
Answer: Use the sort()
Method
You can use the sort()
method in combination with a custom comparison function to sort an array of JavaScript objects by property values. The default sort order is ascending.
The custom comparison function must return an integer equal to zero if both values are equal, an integer less than zero if the first value is less than the second value, and an integer greater than zero if the first value is greater than the second value.
The following example will show you how to sort an array of object by string property values.
Example
Try this code »// Defining comparison function
function compareNames(a, b) {
/* Converting name strings to lowercase to
ignore uppercase and lowercase in comparison */
var nameA = a.name.toLowerCase();
var nameB = b.name.toLowerCase();
if(nameA < nameB) {
return -1;
}
if(nameA > nameB) {
return 1;
}
// Names must be equal
return 0;
}
// Sample object array
var objArr = [
{ name: "Harry", age: 14 },
{ name: "Peter", age: 20 },
{ name: "Alice", age: 18 }
];
// Perform sorting
objArr.sort(compareNames);
console.log(objArr);
Defining comparison function for comparing numbers even much easier. To compare numbers instead of strings, the compare function can subtract b from a. Here's an example that shows how to sort an array of object by numeric property values in ascending order.
Example
Try this code »// Defining comparison function
function compareAges(a, b) {
return a.age - b.age;
}
// Sample object array
var objArr = [
{ name: "Harry", age: 14 },
{ name: "Peter", age: 20 },
{ name: "Alice", age: 18 }
];
// Perform sorting
objArr.sort(compareAges);
console.log(objArr);
See the tutorial on JavaScript Objects to learn more about creating and manipulating objects.
Related FAQ
Here are some more FAQ related to this topic: