How to sort an array of objects by object property in Javascript
The standard way to sort an array of objects is to use the sort (opens new window) method and specify a custom compare function. The compare function can then be used to specify custom code that will be used when comparing objects to determine the order. The compare function takes two parameters a
and b
. a
and b
represent the first and second element to be compared. The compare function should return an integer and if the integer is > 0
then a
should be sorted after b
. If the integer returned is < 0
then a
should be sorted before b
. And finally if 0
is returned then a
and b
are equivalent and can stay in their original order.
JS
Copy code