Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to sort 2d array in Javascript?

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?

like image 975
Jordy Avatar asked Nov 18 '25 11:11

Jordy


2 Answers

You could sort by the delta of the first and second index values.

const array = [[0, 23], [19, 30], [6, 47], [5, 59], [1, 56], [1, 20], [19, 10]];

array.sort((a, b) => a[0] - b[0] || a[1] - b[1]);

console.log(array);
like image 68
Nina Scholz Avatar answered Nov 20 '25 00:11

Nina Scholz


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((a,b)=> {
               if (a[0] === b[0]) {
                  return a[1] - b[1];
                } else {
                  return a[0] - b[0];
                } 
              
              })
            //  .map(a => [parseInt(a.split('.')[0]),parseInt(a.split('.')[1])]);
console.log(result);
.as-console-row-code {
  white-space: initial !important;
}

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

like image 44
Ganesh Avatar answered Nov 19 '25 23:11

Ganesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!