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]);

1

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you but still the appears first :)
Do you mean you want z y x etc? Just switch around the a and b
Yes, alphabetical descending.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.