Sorting JSON Array by Multiple Keys with JavaScript
- By : Mydatahack
- Category : Front-End, Web Technologies
- Tags: Array Sort, JavaScript
JavaScript’s sort() method sorts the elements of an array. Sort() takes callback where you can specify sorting rules.
By writing a small callback function, array of JSON data can be easily sorted. In this example, we use the JSON array that has name and sore. We will sort this date first by score in a descending order and then alphabetical order by name if two people have the same score.
[{ name: "John", score: "432"}, { name: "Joe", score: "125"}, { name: "Zoe", score: "320"}, { name: "Ziggy", score: "532"}, { name: "Dave", score: "211"}, { name: "Sarah", score: "621"}, { name: "Alex", score: "320"}]
Now, here is the call back function that first sort by the first key and second key if the first key has the same value.
When the first key comparison is equal, it goes into the second sorting logic. For descending order sorting, we can return -1 when the first key is bigger than the second key. If you swap the returning value, the sorting order becomes ascending. Magic!
Now, all you need to do is to use this function in a callback for sort().
data.sort(rankingSorter("score", "name"));
Let’s check out how this can be used in the front end. I used pure JavaScript to inject HTML elements. I never really use this method, but sometimes fun to get back to the classic javascripting! To write the injection part, I referred to this page.
It sorts the JSON array and output as a list.
Ranking 1. Name: Sarah, Score: 621 2. Name: Ziggy, Score: 532 3. Name: John, Score: 432 4. Name: Zoe, Score: 320 5. Name: Alex, Score: 320 6. Name: Dave, Score: 211 7. Name: Joe, Score: 125