0

I want to be able to sort a two-dimensional array in order of both the first and second values. I already know you could do something like this:

arr = [[1,4],[3,5],[4,1],[3,2],[1,1]]
arr = arr.sort((a,b)=>{return a[1]-b[1]});
console.log(arr);
arr = arr.sort((a,b)=>{return a[0]-b[0]});
console.log(arr);

but, to simplify the runtime complexity for a coding problem, I want to combine them into one sort. Is there any way to do this?

Brendon Shaw
  • 297
  • 5
  • 21
  • 2
    Possible duplicate of [Javascript - sorting array by multiple criteria](https://stackoverflow.com/questions/28560801/javascript-sorting-array-by-multiple-criteria) – VLAZ Sep 15 '18 at 19:01
  • The complexity is the same regardless of whether you do it once or twice. Maybe you need a different approach entirely. – Ry- Sep 15 '18 at 19:03
  • @Ry- How does the complexity stay the same? To me, it seems like accessing each array element twice would take longer, and that's what I was thinking when I made this post. – Brendon Shaw Oct 02 '18 at 22:16
  • Sorry, I misunderstood your question as asking for an array sorted two different ways (i.e. the two `console.log` values). – Ry- Oct 03 '18 at 02:08

2 Answers2

2

You could just take the deltas without using a ternary.

var array = [[1, 4], [3, 5], [4, 1], [3, 2], [1, 1]];

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

console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You can sort on first elements of each sub array, but if these are equal you move the sorting to the second elements.

arr = [[1,4],[3,5],[4,1],[3,2],[1,1]];
arr.sort(function(a, b) {
    // sort on second eles if the first ones are identical
    // else sort on first...
    return (a[0]== b[0]) ? a[1] - b[1] : a[0] - b[0];
})
console.log(arr);
gaetanoM
  • 41,594
  • 6
  • 42
  • 61