Is there any function in JS to check "If an array exists in a larger array?"
I tried array.includes()
and array.indexOf()
but they didn't work for me...
for example I except a true return value here:
parent = [[a,b],[c,d],[e,f]]
child = [c,d]
Is there any function in JS to check "If an array exists in a larger array?"
I tried array.includes()
and array.indexOf()
but they didn't work for me...
for example I except a true return value here:
parent = [[a,b],[c,d],[e,f]]
child = [c,d]
Your includes
fails because you're trying to match reference. A well detailed explanation you can see on this answer https://stackoverflow.com/a/54363784/9624435
You can use filter
and every
let parent = [['a','b'],['c','d'],['e','f']];
let child = ['c','d'];
let result = parent.filter(arr => arr.every(v => child.includes(v)));
console.log(result);
Let's focus on why .includes
fail.
Array.includes
uses following function to check equality:
function sameValueZero(x, y) {
return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
}
Since you have arrays as element, they are copied using references, so you are checking references of arrays instead. Hence it fails.
Following is a sample:
const item1 = ['a', 'b'];
const item2 = ['c', 'd'];
const item3 = ['e', 'f']
const parent = [item1, item2, item3]
const child = item3;
console.log(parent.includes(child))
Hence, you will have to go deeper and check individual values.