Categories
JavaScript Answers

How to sort 2-dimensional array by column value with JavaScript?

Spread the love

To sort 2-dimensional array by column value with JavaScript, we can get the value by the index.

For instance, we write

const arr = [
  [12, "AAA"],
  [12, "BBB"],
  [12, "CCC"],
  [28, "DDD"],
  [18, "CCC"],
  [12, "DDD"],
  [18, "CCC"],
  [28, "DDD"],
  [28, "DDD"],
  [58, "BBB"],
  [68, "BBB"],
  [78, "BBB"],
];

const sorted = arr.sort((a, b) => {
  return a[0] - b[0];
});

to call sort with a callback that gets the first value from each nested array and compare them to sort the entries by the first value and return the sorted array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *