Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array .includes() giving unexpected behavior

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.

like image 728
Erich Purpur Avatar asked Mar 01 '26 07:03

Erich Purpur


2 Answers

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)
like image 194
Jeremy Thille Avatar answered Mar 02 '26 19:03

Jeremy Thille


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.

like image 33
Jeff B Avatar answered Mar 02 '26 19:03

Jeff B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!