How to test if nested arrays are equal to each other

61 views Asked by At

I have a maze generator that generates walls per "cell". This means that there are duplicate walls - e.g. the left wall of one cell is exactly the same as the right wall of the cell to the left. I want to generate a maze and extract the data to a different program in the format [x, y, type] where type is 0 - horizontal or 1 - vertical. I was able to convert the data, but now I have an array with duplicates. (e.g. [[0, 0, 0], [0, 1, 0], [0, 0, 0]...] and you can see the index 0 and 2 elements are equal.) I want to remove these duplicates.

I tried making a function removeDuplicates() that takes an array.

function removeDuplicates(arr) {
    tempArr = [];
    for(var i = 0; i < arr.length; i ++) {
        var found = false;
        for(var j = 0; j < tempArr.length; j ++) {
            if(tempArr[j].equals(arr[i])) {
                found = true;
            }
        }
        if(found === false) {
            tempArr.push(arr[i]);
        }
    }
}

When I run the code, it tells me that tempArr[j].equals is not a function. Why? What do I need to change to test for equal arrays? The operator == did not work either.

1

There are 1 answers

0
James On

Assuming that the array in arr[i] is one level deep only (no nested stuff) you can try

if (tempArr[j].every((el, k) => arr[i][k] === el))