Brendon Shaw
Brendon Shaw

Reputation: 298

Reduce Runtime Complexity for Matrix Sort

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?

Upvotes: 0

Views: 101

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386570

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

Upvotes: 2

gaetanoM
gaetanoM

Reputation: 42044

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

Upvotes: 1

Related Questions