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?
CodePudding user response:
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))