2

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?

Jordy
  • 1,802
  • 2
  • 6
  • 25

4 Answers4

6

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

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

Ganesh Nemade
  • 1,504
  • 12
  • 17
1

Similar to this answer, but works for inner number arrays of any length (not just 2 elements):

function sortByNumberElements(arrA, arrB) {
  let diff = 0;
  const length = Math.min(arrA.length, arrB.length);
  for (let i = 0; i < length; i += 1) {
    diff = arrA[i] - arrB[i];
    if (diff) break;
  }
  return diff;
}

const input = [[0,23],[19,30],[6,47],[5,59],[1,56],[1,20],[19,10]];
input.sort(sortByNumberElements);

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

console.log("Equal?", JSON.stringify(input) === JSON.stringify(expected));
jsejcksn
  • 27,667
  • 4
  • 38
  • 62
0

The original question approach with added destructuring:

    const arr = [[0, 23], [19, 30], [6, 47], [5, 59], [1, 56], [1, 20], [19, 10]];
    
    const result = arr
      .map(([a, b]) => [a, b, a + b / 100])
      .sort(([, , key1], [, , key2]) => key1 - key2)
      .map(([a, b]) => [a, b]);
    
    console.log(result)
protob
  • 3,317
  • 1
  • 8
  • 19