I was reading a social post and found that Array.sort() works great across all the browser. I thought to write small demo to show powerful compare function to sort object type array on given property.
Example: Array.sort()
Also, Array.sort() is a string sort by default! Should be used for string like type only!
1 2 3 |
var unorderedArray = [1, 2, 22, 11, 55]; var orderedArray = unorderedArray.sort(); console.log(orderedArray); |
So, you can not use for Array.sort() for numeric sort! 🙁
But, you can use compare callback function to work with Object type Array very efficiently.
Example: Array.sort(compareFunction)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
var unorderedObjectArray = [ { Name: "Gaurang", Last: "Jadia", Zipcode: 91801 }, { Name: "Steve", Last: "Jobs", Zipcode: 95014 }, { Name: "Bill", Late: "Gates", Zipcode: 98052 } ]; var orderedObjectArray = unorderedObjectArray.sort(function(x, y) { if (x.Name < y.Name) { return -1; } else if (y.Name < x.Name) { return 1; } else { return 0; } }); console.log(orderedObjectArray); |
Read: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort?redirect=no