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

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

Barbara Streisand
Release: 2024-11-15 19:11:05
Original
254 people have browsed it

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"]]
Copy after login

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

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

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

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

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!

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