Home > front end >  JavaScript: sort 2d arrays alphabetically according to the first items of the sub arrays
JavaScript: sort 2d arrays alphabetically according to the first items of the sub arrays

Time:09-22

I have a 2d arrays like this:

const arrays = [
  ['Ethan', '[email protected]', '[email protected]', '[email protected]'],
  ['David', '[email protected]', '[email protected]', '[email protected]'],
  ['Lily', '[email protected]', '[email protected]', '[email protected]'],
  ['Gabe', '[email protected]', '[email protected]', '[email protected]'],
  ['Ethan', '[email protected]', '[email protected]', '[email protected]'],
]

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', '[email protected]', '[email protected]', '[email protected]'],
  ['David', '[email protected]', '[email protected]', '[email protected]'],
  ['Lily', '[email protected]', '[email protected]', '[email protected]'],
  ['Gabe', '[email protected]', '[email protected]', '[email protected]'],
  ['Ethan', '[email protected]', '[email protected]', '[email protected]'],
]


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

CodePudding user response:

I think you want something like this:

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

More about localeCompare here

CodePudding user response:

Try this version:

var arrays = [
  ['Ethan', '[email protected]', '[email protected]', '[email protected]'],
  ['David', '[email protected]', '[email protected]', '[email protected]'],
  ['Lily', '[email protected]', '[email protected]', '[email protected]'],
  ['Gabe', '[email protected]', '[email protected]', '[email protected]'],
  ['Ethan', '[email protected]', '[email protected]', '[email protected]'],
];

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

  • Related