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.