1

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?

1 Answer 1

1

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))

Sign up to request clarification or add additional context in comments.

10 Comments

thank you very much, I have another question. How could I remove duplicates from this array? Do you have any idea? It would help me a lot
A simple way would be to convert it to a Set then back to an Array. Just like this: let newArray = [...new Set(oldArray)]
I tried it but it doesn't work with this type of 2D array, it works with 1D array
@codproe Ah yes, sorry. In that case, I'd just loop over every subarray of the 2d array. Like this: let newTwoD = oldTwoD.map(arr => [...new Set(arr)])
I tried this array [5, 6], [1, 2], [1, 3], [1, 1], [1,1] and result was [5, 6], [1, 2], [1, 3], [1], [1]
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.