1

I have a simple 2D array that I want to sort with two conditions.

[ [ "the,", 3 ], [ "who,", 3 ], [ "take,", 4 ], [ "over,", 4 ], [ "world,", 5 ] ]
  1. Sort by number ascending

  2. Then sort alphabetically descending

Expected result would be the who word. First step is achieved with below code:

arraySorted = arrCom.sort((a, b) => a[1] - b[1] || a[0] - b[0]);

marcin2x4
  • 1,321
  • 2
  • 18
  • 44

1 Answers1

1

If the first comparison comes out to 0 (same number), use localeCompare to compare alphabetically:

const arr = [ [ "the,", 3 ], [ "who,", 3 ], [ "take,", 4 ], [ "over,", 4 ], [ "world,", 5 ] ];
arr.sort(
  (a, b) => a[1] - b[1] || b[0].localeCompare(a[0])
);
console.log(arr);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320