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
- Compare first element, if first element is equal, compare second ending elemennt
So [0, 6] should be before [0,9]...
return sort(a.slice(1, 2), b.slice(1,2))