Categories
JavaScript Answers

How to sort a JavaScript array with arrays in it by string?

Spread the love

To sort a JavaScript array with arrays in it by string, we call the sort method.

For instance, we write

const comparator = (a, b) => {
  if (a[1] < b[1]) return -1;
  if (a[1] > b[1]) return 1;
  return 0;
};

const myArray = [
  [1, "alfred", "..."],
  [23, "berta", "..."],
  [2, "zimmermann", "..."],
  [4, "albert", "..."],
];

const sortedMyArray = myArray.sort(comparator);

to call myArray.sort with the comparator function to sort the array in ascending order by the 2nd entry of each array.

We do the comparison with the comparison operators and return -1 if a[1] comes before b[1].

And we return 1 when a[1] comes after b[1] to sort in ascending order.

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 *