I have a 2d array like this:
[[0,23],[19,30],[6,47],[5,59],[1,56],[1,20],[19,10]]
How can I sort that based on the value of pairs like this:
[[0,23],[1,20],[1,56],[5,59],[6,47],[19,10],[19,30]]
Here is my attempt:
let arr = [[0,23],[19,30],[6,47],[5,59],[1,56],[1,20],[19,10]];
let result = arr
.map(a => `${a[0]}.${a[1]}`)
.sort()
.map(a => [parseInt(a.split('.')[0]),parseInt(a.split('.')[1])]);
console.log(result);
.as-console-row-code {
white-space: initial !important;
}
The below code still gives wrong result. Any advice for a simple solution?
4
Answers
You could sort by the delta of the first and second index values.
I have commented the map statemens not to convert them into strings. that makes it sorted lexicographically.
We can use custom sort function here as shown above
Similar to this answer, but works for inner number arrays of any length (not just 2 elements):
The original question approach with added destructuring: