Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort 2D array of pairs in JavaScript

I need to sort 2D array of pairs in JavaScript.

const a = [
  [1, 1],
  [1, 2],
  [1, 3],
  [5, 6]
]
const b = [
  [5, 6],
  [1, 2],
  [1, 3],
  [1, 1]
]
b.sort((c, d) => d[0] + d[1] - c[0] + c[1]);
console.log(b)

function compare(a, b) {
  if (a.length != b.length) return false;
  for (let i = 0; i < b.length; i++)
    for (let j = 0; j < b[i].length; j++)
      if (a[i][j] !== b[i][j]) return false;
  return true;
}
console.log(compare(a, b))

I want to sort array b to be equal to array a. Of course real life array is much longer. This is just an example.

I have written function for comparing, but sort function doesn’t work properly. Could you please help me to fix this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The issue isn’t your compare function, but instead your .sort() call.

First, d[0] + d[1] - c[0] + c[1] is backwards. You should subtract the elements of d from c, not the other way around. Like this: c[0] + c[1] - d[0] + d[1].

Second, you have an order of operations error. You need to subtract the elements of d from c, but your current code subtracts one element of d and adds the other. You need to distribute the negative sign, just like this: c[0] + c[1] - d[0] - d[1]

const a = [
  [1, 1],
  [1, 2],
  [1, 3],
  [5, 6]
]
const b = [
  [5, 6],
  [1, 2],
  [1, 3],
  [1, 1]
]
b.sort((c, d) => c[0] + c[1] - d[0] - d[1]);
console.log(b)

function compare(a, b) {
  if (a.length != b.length) return false;
  for (let i = 0; i < b.length; i++)
    for (let j = 0; j < b[i].length; j++)
      if (a[i][j] !== b[i][j]) return false;
  return true;
}
console.log(compare(a, b))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading