Sorting a Two-Dimensional Array by Column Value
Sorting a two-dimensional array by the value of a specific column is a common programming task. In JavaScript, this can be achieved using the sort() method, which takes a comparison function as its argument.
Example: Sorting by First Column
The provided JavaScript code snippet demonstrates how to sort a two-dimensional array by the values in the first column:
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; } }
In this example, the sortFunction takes two elements (a and b) from the array and compares their first values (a[0] and b[0]). If the values are equal, the function returns 0, indicating that the order should remain the same. If a[0] is less than b[0], the function returns -1, indicating that a should come before b. Otherwise, it returns 1, indicating that a should come after b.
Sorting by Second Column
To sort the array by the second column, simply modify the sortFunction to compare the second values instead:
a.sort(compareSecondColumn); function compareSecondColumn(a, b) { if (a[1] === b[1]) { return 0; } else { return (a[1] < b[1]) ? -1 : 1; } }
After sorting, the array will be in ascending order based on the values in the specified column.
The above is the detailed content of How do you sort a two-dimensional array by a specific column in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!