Problem:
How can I sort a 2D array in JavaScript based on the values in a specific column?
Code Snippet:
To sort a 2D array by the first column, use the following code:
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; } }
Explanation:
The sort() method sorts an array in place. In this case, we pass a sortFunction that compares the first elements of the two arrays a and b and returns -1 if a should come before b, 1 if b should come before a, or 0 if they are equal.
Sorting by the Second Column:
To sort by the second column, replace the sortFunction with the following:
function compareSecondColumn(a, b) { if (a[1] === b[1]) { return 0; } else { return (a[1] < b[1]) ? -1 : 1; } }
Output:
The sorted array will look like this:
[ [12, 'AAA'], [18, 'DDD'], [28, 'CCC'], [58, 'BBB'] ]
The above is the detailed content of How to Sort a 2D Array in JavaScript by Column Value?. For more information, please follow other related articles on the PHP Chinese website!