Reputation: 61
I want to sort nested array (array inside an array) i.e My array looks like this
const input = [[3,9],[7,12],[3,8],[6,8],[9,10],[2,9],[0,9],[3,9],[0,6],[2,8]]
To do that I wrote this logic
const input = [[3,9],[7,12],[3,8],[6,8],[9,10],[2,9],[0,9],[3,9],[0,6],[2,8]]
function sort (a,b) {
if (a[0] < b[0]) return -1
if (a[0] > b[0]) return 1
if (a[0] === b[0]) {
if (a.length > 1 && b.length > 1) {
return sort(a.slice(0, 1), b.slice(0,1))
}
else return 0
}
}
console.log(input.sort((a,b) => {
return sort(a,b)
}))
but this is giving first element as [0,9]
instead of [0, 6]
and [2, 9]
instead of [2,8]
so on.
What I want is
So [0, 6]
should be before [0,9]
...
Upvotes: 0
Views: 364
Reputation: 371233
All you need for the callback is a[0] - b[0] || a[1] - b[1]
:
const input = [[3,9],[7,12],[3,8],[6,8],[9,10],[2,9],[0,9],[3,9],[0,6],[2,8]]
console.log(input.sort((a,b) => a[0] - b[0] || a[1] - b[1]))
If the array is of arbitrary length, then you do need a separate named function:
const sort = (a, b) => a[0] - b[0] || sort(a.slice(1), b.slice(1));
const input = [[3,9],[7,12],[3,8],[6,8],[9,10],[2,9],[0,9],[3,9],[0,6],[2,8]]
console.log(input.sort((a,b) => a[0] - b[0] || a[1] - b[1]))
Upvotes: 4