Home > OS >  How can I compare two 2D arrays? In javascript
How can I compare two 2D arrays? In javascript

Time:12-01

I have a problem to compare two 2D arrays in javascript. It should output "true" if the two 2D arrays are the same.

The code I tried:

`

function check(){
   
    if (data.every() === solution.every()){
        alert("example");
    } else {
        console.log("Data Array: "   data);
        console.log("Solution Array: "   solution);
    }
  
}

`

I think my solution only works with two 1D arrays. I hope someone can help me and teach me something.

Note: I only use jquery and nativ js.

Thanks in advance.

~Luca

CodePudding user response:

I would assume something like this would work :

function test(array1, array2)
{
 if(array1.length !== array2.length) return false;

for(let i=0;i<array1.length;i  )
{
 if(array1[i].length !== array2[i].length) return false;
 for(let j=0;j<array1[i].length;j  )
 {
  if(array1[i][j] !== array2[i][j]) return false;
 }
}
return true;
}

You could also do a recursive version that would work for array of N-dimensions, but it you need only 2, the above is fine.

CodePudding user response:

This code will work for any number of dimensions:

const random2dArray = (n,m) => Array(n).fill(0)
  .map(_=>Array(m).fill(0).map(_=>10*Math.random()|0))

const arrEq = (a,b) => Array.isArray(a) ?
  a.length===b.length && a.every((e,i)=>arrEq(e,b[i])) : a===b

const a = random2dArray(3,3)
const b = random2dArray(3,3)
const c = random2dArray(3,5)
const d = random2dArray(6,7)
const e = structuredClone(a)

console.log(arrEq(a,b))
console.log(arrEq(a,c))
console.log(arrEq(a,d))
console.log(arrEq(a,e))

CodePudding user response:

A common solution that many people suggest is to use JSON.stringify(). This allows us to serialize each array and then compare the two serialized strings. A simple implementation of this might look something like this:

function check(){
   
    if ( JSON.stringify(data) === JSON.stringify(solution) ){
        alert("example");
    } else {
        console.log("Data Array: "   data);
        console.log("Solution Array: "   solution);
    }
}
  • Related