Languages
[Edit]
EN

JavaScript - sort two dimensional array by column value

0 points
Created by:
Violetd
925

In this article, we would like to show you how to sort a two-dimensional array by column value in JavaScript.

Practical example

In this example, we create a custom compare function to sort a 2D array by first column value.

// ONLINE-RUNNER:browser;

const array = [
    [2, 'a'],
    [1, 'c'],
    [4, 'b'],
    [3, 'd'],
];

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

array.sort(compareFunction);

console.log(JSON.stringify(array)); // [[1,"c"],[2,"a"],[3,"d"],[4,"b"]]

By second column value:

// ONLINE-RUNNER:browser;

const array = [
    [2, 'a'],
    [1, 'c'],
    [4, 'b'],
    [3, 'd'],
];

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

array.sort(compareFunction);

console.log(JSON.stringify(array)); // [[2,"a"],[4,"b"],[1,"c"],[3,"d"]]

 

References

  1. Array.prototype.sort() - JavaScript | MDN

Alternative titles

  1. JavaScript - sort 2 dimensional array by column value
  2. JavaScript - sort 2D array by column value
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join