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

How to Sort a Two-Dimensional Array by Column Value in JavaScript?

Mary-Kate Olsen
Release: 2024-11-21 09:31:13
Original
355 people have browsed it

How to Sort a Two-Dimensional Array by Column Value in JavaScript?

Sorting a Two-Dimensional Array by Column Value in JavaScript

To sort a 2D array by its column values in JavaScript, you can use the Array.sort() method with a custom comparison function. This function compares the elements in the specified column and determines the sort order.

Consider the following example:

var a = [[12, 'AAA'], [58, 'BBB'], [28, 'CCC'],[18, 'DDD']];
Copy after login

To sort this array by the first column, you can use the following code:

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

The sortFunction compares the first elements of the two rows being compared (a[0] and b[0]) and returns -1 if the first element of a is less than the first element of b, 1 if it is greater than, and 0 if they are equal. This defines the sort order, and the Array.sort() method will arrange the array accordingly.

To sort by the second column, you can modify the sort function:

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

This function compares the second elements of the rows being compared. Using these methods, you can easily sort a 2D array by any column value in JavaScript.

The above is the detailed content of How to Sort a Two-Dimensional Array by Column Value 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