-3

I have an array: arr = [[3,2],[1,2],[2,1]] and I'd like to sort it to: arr = [[1,2],[3,2],[2,1]]. What I am doing is sorting by subArr[1] first then in case two elements have equal subArr[1], then sort only those two elements by their subArr[0].

Here is what I did, which I think is stupid for invoking the .sort() method twice.

function sortArr(array) {
  let arr = array;
  arr.sort((a, b) => {
    return b[1] - a[1];
  });
  arr.sort(function (a, b) {
    if (a[1] == b[1]) {
      return a[0] - b[0];
    }
    return b[1] - a[1];
  });
  return arr;
}
heapnoob
  • 11
  • 1

1 Answers1

1

You can do this in one sort:

const arr = [[3,2],[1,2],[2,1]];

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

console.log(arr);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48