Sorting Two-Dimensional Arrays by Column Values in JavaScript
In this article, we will explore how to sort a two-dimensional array in JavaScript by a specific column value.
Problem Statement
Given a two-dimensional array represented as an array of arrays, each sub-array containing two elements, the task is to sort the array in ascending order based on the values in the first column (column with index 0).
Solution
JavaScript provides a convenient method, sort(), that can be utilized to sort multidimensional arrays. Let's break down the provided 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 sortFunction is passed as the argument to the sort() method. This function compares two sub-arrays' first elements (a[0] and b[0]) and returns:
By default, sort() uses the returned values to determine the ordering of the sub-arrays, sorting them in ascending order.
Sorting By Second Column
To sort by the second column, the sortFunction can be modified to compare second column values:
a.sort(compareSecondColumn); function compareSecondColumn(a, b) { if (a[1] === b[1]) { return 0; } else { return (a[1] < b[1]) ? -1 : 1; } }
This enables flexibility in sorting by different columns based on the specific requirements.
The above is the detailed content of How Can You Sort a Two-Dimensional Array by Column Value in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!