Sorting 2D Arrays in JavaScript
How can I sort a 2D array by column value in JavaScript?
Suppose we have a 2D array with the following format:
[[12, "AAA"], [58, "BBB"], [28, "CCC"], [18, "DDD"]]
We want to sort this array by the first column, resulting in:
[[12, "AAA"], [18, "DDD"], [28, "CCC"], [58, "BBB"]]
Solution:
Sorting a 2D array by column value is straightforward in JavaScript. Here's how you can do it:
var a = [[12, 'AAA'], [58, 'BBB'], [28, 'CCC'],[18, 'DDD']]; a.sort(sortFunction); function sortFunction(a, b) { if (a[0] === b[0]) { return 0; } else { return (a[0] < b[0]) ? -1 : 1; } }
This function uses the following rules:
To sort the array by the second column, simply replace a[0] with a[1] in the comparison function.
a.sort(compareSecondColumn); function compareSecondColumn(a, b) { if (a[1] === b[1]) { return 0; } else { return (a[1] < b[1]) ? -1 : 1; } }
Refer to the JavaScript documentation for more information on the sort function.
The above is the detailed content of How to Sort a 2D Array by Column Value in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!