0

TL;DR: the JavaScript code below returns false where I'm expecting a true, what's the best workaround?

 console.log([['a']].includes(['a']))

I'm pushing arrays into arrays (to work with google sheets ranges in apps script, but the behaviour is the same in regular JavaScript).

I'd like to check if my parent array (let's call it [['a']]) contains specific child array (such as ['a']).

Unfortunately array.includes() doesn't seem to work as expected when the parameter is an array. (the code above returns false when it should be true as far as I know)

Am I missing anything? What do you think would be the best workaround?

Rubén
  • 34,714
  • 9
  • 70
  • 166
  • By design. Learn about referential / object identity equality. Two arrays --though they may have the same *value*s-- occupy two different places in memory and are thus not equal to each other. – tehhowch Mar 30 '20 at 12:57

2 Answers2

3

The problem is array comparison.

console.log(['a'] == ['a']); //false

As the .includes() method loops through the array on which it is being called, it checks each element to see if it is equal to the value being tested for, until it finds a match, or checks every element of the array. As you can see above, when the value being tested is an array, it will not work.

A work around would be to write your own .includes() function in which you loop through all the child arrays in the parent array, and for each child array, loop through every element, testing whether it is equal to the corresponding element in the test array. You can use the .every() method for this.

let array = [['a']];

function includesArray(parentArray, testArray) {
    for (let i = 0; i < parentArray.length; i++) {
        if (parentArray[i].every(function(value, index) { return value === testArray[index]})) {
            return true;
        }
    }
    return false;
}

console.log(includesArray(array, ['a'])); //true
console.log(includesArray(array, ['b'])); //false
0

One quick alternative is to compare the JSON strigified arrays instead of comparing arrays directly.

console.log([['a']].map(x => JSON.stringify(x)).includes(JSON.stringify(['a'])))
Siva K V
  • 10,561
  • 2
  • 16
  • 29