0

I have looked at other posts that supposedly have solved this issue, but this method still doesn't work for me. I had run into an error in a larger program I was writing but I narrowed the error to this method.

I set a cell to =isMatch( {1,2,3} , {1,2,3} ) to verify my method works. The cell computes to False, and I don't know why or how to fix it.

Before I checked stackoverflow, I had originally written code identical to the answer of this post.

Here is the code I currently have.

function isMatch(arr1,arr2){//Returns True if same Array values in same location
  if(arr1.length !== arr2.length)
        return false;
    for(var i =0; i<arr1.length; i++) {
        if(arr1[i] !== arr2[i])
            return false;
    }

    return true;
}
jakal02
  • 3
  • 3

1 Answers1

1

You're comparing a 2D array. {1,2,3} === [[1,2,3]] and not [1,2,3].

To compare a n dimensional array, you can recurse:

function isMatch(arr1, arr2) {
  if (typeof arr1 !== typeof arr2)
    throw new TypeError('Arrays or elements not of same type!');
  if (Array.isArray(arr1))
    return (
      arr1.length === arr2.length && arr1.every((e, i) => isMatch(e, arr2[i]))
    );
  return arr1 === arr2;
}

console.info(isMatch([[1], [2]], [[1], [2]]));
console.info(isMatch([[1, 2]], [[1, 2]]));
console.info(isMatch([[1, 2]], 1));
TheMaster
  • 45,448
  • 6
  • 62
  • 85