Tyler Morales
Tyler Morales

Reputation: 1848

How to sort a deeply sorted array numerically in ascending order?

I am trying to sort each array in an array, however, when I sort each nested array, the arrays are not sorted. This is what I've been doing so far:

let triplets = [ [ 1, -1, 0 ], [ 1, -1, 0 ], [ 1, 0, -1 ] ]

let sortedArrays = triplets.sort((a, b) => a[0] - b[0] || a[1] - b[1])

console.log(sortedArrays) // [ [ 1, -1, 0 ], [ 1, -1, 0 ], [ 1, 0, -1 ] ]

// Expect: [ [-1, 0, 1], [-1, 0, 1], [-1, 0, 1] ]

Obviously, they are not sorted. In the first sub array, 1 does not come before 1. Why is this the case and is there a better way to sort these?

Upvotes: 1

Views: 34

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371158

It looks like you don't need to sort the triplets, you need to sort each subarray - so call .sort on the subarrays, not on the outer array.

let triplets = [ [ 1, -1, 0 ], [ 1, -1, 0 ], [ 1, 0, -1 ] ];
for (const subarr of triplets) {
  subarr.sort((a, b) => a - b);
}
console.log(triplets);

Upvotes: 1

Related Questions