Home > Web Front-end > JS Tutorial > body text

How do you sort a two-dimensional array by a specific column in JavaScript?

Linda Hamilton
Release: 2024-11-20 12:08:12
Original
430 people have browsed it

How do you sort a two-dimensional array by a specific column in JavaScript?

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;
    }
}
Copy after login

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;
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template