Most people would assume that sort would take no method and simply sort the basic items within the array:
[1, 3, 9, 2].sort();
// Returns: [1, 2, 3, 9]
[1, "a", function(){}, {}, 12, "c"].sort();
// Returns: [1, 12, Object, "a", "c", function (){}]
But nay, broseph! If you provide a function expression to the sort
method, you can sort objects within the array using simple logic. Let's
say you have an array of objects representing persons and you want to
sort them by age. Oh yes, it can be done, and quite easily:[
{ name: "Robin Van Persie", age: 28 },
{ name: "Theo Walcott", age: 22 },
{ name: "Bacary Sagna", age: 26 }
].sort(function(obj1, obj2) {
// Ascending: first age less than the previous
return obj1.age - obj2.age;
});
// Returns:
// [
// { name: "Theo Walcott", age: 22 },
// { name: "Bacary Sagna", age: 26 },
// { name: "Robin Van Persie", age: 28 }
// ]
The anonymous function returns whether or not the first object's age
is less than the second's, thus sorting the entire array in ascending
order by age. Reverse the first and second arguments to sort in
descending order.So brochacho, now you know how to sort an array of objects using JavaScript. Get to it!