I needed to sort an array of objects in JavaScript recently and was quite frankly amazed by 2 things:
- I’d never done it before in 7+ years of JavaScript
- It’s really rather easy!
JavaScript has Array.sort
that will order an array’s contents in ascending alphabetical order. So:
var testArray = ['c', 'a', 'b']; testArray.sort(); //sorts as a, b, c
The default sort does not sort numeric data, it is purely a character based sort, so:
var testArray = [3, 1, 2, 19]; testArray.sort(); //sorts as 1, 19, 2, 3
Array.sort
takes a function as an optional parameter. The function takes two parameters which are the two elements in the array that you are comparing. The function needs to compare these two elements and figure out which should take precedence:
- Less than 0: First item is before the second
- 0: identical items
- More than 0: First item is after the second
If we want to sort these items in a descending order then we need to pass a function to the Array.sort
do something like the following:
function ascending(a, b){ if (a === b) { return 0; } else if (b > a) { return 1; } return -1; } var testArray = ['c', 'a', 'b']; testArray.sort(ascending); //sorts as c, b, a
Wasn’t this post about sorting arrays of objects?
Sorry, I digress, but that was Array.sort
101. Below are a couple of simple ideas for sorting a simple object array – these could be replaced by whatever fancy pants sorting logic you need, but hopefully this will save someone, somewhere some faffing and Googling.
var arrayOfPeople = [ {name:"Rick Huby", email:"rick@test.com", age:30}, {name:"Alan Smith", email:"mrsmith@test.com", age:25}, {name:"Jo Jenkins", email:"iamjo@test.com", age:40}, {name:"Dave Smith", email:"dave@test.com", age: 35} ]; function orderByNameAscending(a, b) { if (a.name == b.name) { return 0; } else if (a.name > b.name) { return 1; } return -1; } function orderByEmailAscending(a, b) { if (a.email == b.email) { return 0; } else if (a.email > b.email) { return 1; } return -1; } function orderByAgeAscending(a, b) { return a.age - b.age; } arrayOfPeople.sort(orderByNameAscending); arrayOfPeople.sort(orderByEmailAscending); arrayOfPeople.sort(orderByAgeAscending);
If you want to progress these then I would at least put some defensive logic in to ensure that calling the object attributes (a.name
etc.) doesn’t cause a runtime error (try/catch or some rudimentary a.name === undefined
check may be enough).