JavaScript: sort 2d arrays alphabetically according to the first items of the sub arrays

Viewed 29

I have a 2d arrays like this:

const arrays = [
  ['Ethan', 'Ethan1@m.co', 'Ethan2@m.co', 'Ethan0@m.co'],
  ['David', 'David1@m.co', 'David2@m.co', 'David0@m.co'],
  ['Lily', 'Lily0@m.co', 'Lily0@m.co', 'Lily4@m.co'],
  ['Gabe', 'Gabe1@m.co', 'Gabe4@m.co', 'Gabe0@m.co'],
  ['Ethan', 'Ethan2@m.co', 'Ethan1@m.co', 'Ethan0@m.co'],
]

I want to sort this 2d array so that the first item, i.e. the name, of each sub array is sorted alphabetically and sub-arrays that share the same name should be adjacent to each other after being sorted.

I tried to do this but it doesn't seem to be working:

const arrays = [
  ['Ethan', 'Ethan1@m.co', 'Ethan2@m.co', 'Ethan0@m.co'],
  ['David', 'David1@m.co', 'David2@m.co', 'David0@m.co'],
  ['Lily', 'Lily0@m.co', 'Lily0@m.co', 'Lily4@m.co'],
  ['Gabe', 'Gabe1@m.co', 'Gabe4@m.co', 'Gabe0@m.co'],
  ['Ethan', 'Ethan2@m.co', 'Ethan1@m.co', 'Ethan0@m.co'],
]


const sortedArrays = arrays.sort(([nameA, nameB]) => nameA - nameB) // still not sorted

2 Answers

I think you want something like this:

arrays.sort((a,b) => a[0].localeCompare(b[0]))

More about localeCompare here

Try this version:

var arrays = [
  ['Ethan', 'Ethan1@m.co', 'Ethan2@m.co', 'Ethan0@m.co'],
  ['David', 'David1@m.co', 'David2@m.co', 'David0@m.co'],
  ['Lily', 'Lily0@m.co', 'Lily0@m.co', 'Lily4@m.co'],
  ['Gabe', 'Gabe1@m.co', 'Gabe4@m.co', 'Gabe0@m.co'],
  ['Ethan', 'Ethan2@m.co', 'Ethan1@m.co', 'Ethan0@m.co'],
];

arrays.sort((arrA, arrB) => arrA[0].localeCompare(arrB[0]));
console.log(arrays);

Related