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.
// 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.
Use the
sort()MethodYou 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.
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.
need an explanation for this answer? contact us directly to get an explanation for this answer