Categories
JavaScript Answers

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

Spread the love

Sometimes, we want to sort 2 dimensional array by column value with JavaScript.

In this article, we’ll look at how to sort 2 dimensional array by column value with JavaScript.

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

To sort 2 dimensional array by column value with JavaScript, we can use the array sort method.

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 sortedArr = arr.sort((a, b) => {
  return a[0] - b[0];
});

to call arr.sort with a callback that sorts each array in arr by the value of the first entry in each array in ascending order.

a and b are entries in arr.

Conclusion

To sort 2 dimensional array by column value with JavaScript, we can use the array sort method.

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 *