array .includes() giving unexpected behavior

Viewed 81

I have a very simple array and am checking to see if it .includes() a value. But it is not returning the result I expect.

var myArray = [['noca', 'North Cascades National Park'], ['shen', 'Shenandoah National Park']];

var myItem = ['noca', 'North Cascades National Park'];

myArray.includes(myItem);   //returns false

Why is myArray.inclues(myItem) returning false? This seems like the simplest thing in the world. It should return true.

4 Answers

The following is adopted from this answer:

https://stackoverflow.com/a/48538239/2096053

var datas= [
  ["aaa", "bbb"],
  ["ddd", "eee"]
];

function exists(arr, search) {
    return arr.some(row => 
        Array.isArray(row) &&
        Array.isArray(search) &&
        row.length === search.length &&
        row.every((val, index) => val === search[index])
)
};

console.log(exists(datas, ['aaa', 'bbb'])); // TRUE
console.log(exists(datas, ['aaa']));        // FALSE
console.log(exists(datas, ['xxx']));        // FALSE
console.log(exists(datas, 'xxx'));          // FALSE

You need to use a combination of some and includes to properly go over the array.

I have updated this answer to search on arrays.

Checking if an array contains another array is tricky. As I said in the comments, ['noca'] === ['noca'] returns false because these are two distinct arrays.

On the other hand, JSON.stringify(['noca']) === JSON.stringify(['noca']) returns true because it compares two strings, so you can use that :

var myArray = [['noca', 'North Cascades National Park'], ['shen', 'Shenandoah National Park']];
var myItem = ['noca', 'North Cascades National Park'];

const checkContains = (parent, child) => parent.some(arr => JSON.stringify(arr)===JSON.stringify(child))

console.log( checkContains(myArray, myItem) )
console.log( checkContains(myArray, ["test"]) )
console.log( checkContains(myArray, ["noca"]) ) // No false positive (works as intended)

This is an expected behaviour, because array is an object and it is referenced. So, your array element and actual element to compare will not be equal and Array.prototype.includes() will return false.

If you try following, it will return true.

var myItem = ['noca', 'North Cascades National Park'];

var myArray = [myItem, ['shen', 'Shenandoah National Park']];

myArray.includes(myItem);   //returns true

You are not using it correctly. References between arrays are not the same.

Check doc: includes

You should iterate over arrays and use every for example.

Related