Home  >  Article  >  Web Front-end  >  How to Sort a Two-Dimensional Array by Column Value in JavaScript?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-21 09:31:13375browse

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']];

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;
    }
}

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;
    }
}

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!

Statement:
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