Home >Web Front-end >JS Tutorial >How to Sort a 2D Array by Column Value in JavaScript?

How to Sort a 2D Array by Column Value in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-11-15 19:11:05326browse

How to Sort a 2D Array by Column Value in JavaScript?

Sorting 2D Arrays in JavaScript

How can I sort a 2D array by column value in JavaScript?

Suppose we have a 2D array with the following format:

[[12, "AAA"], [58, "BBB"], [28, "CCC"], [18, "DDD"]]

We want to sort this array by the first column, resulting in:

[[12, "AAA"], [18, "DDD"], [28, "CCC"], [58, "BBB"]]

Solution:

Sorting a 2D array by column value is straightforward in JavaScript. Here's how you can do it:

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

This function uses the following rules:

  • If the elements in the first column are equal, return 0.
  • If the element in the first column of the first array is less than that of the second, return -1.
  • If the element in the first column of the first array is greater than that of the second, return 1.

To sort the array by the second column, simply replace a[0] with a[1] in the comparison function.

a.sort(compareSecondColumn);

function compareSecondColumn(a, b) {
    if (a[1] === b[1]) {
        return 0;
    }
    else {
        return (a[1] < b[1]) ? -1 : 1;
    }
}

Refer to the JavaScript documentation for more information on the sort function.

The above is the detailed content of How to Sort a 2D 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