-3

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]
Kamil Naja
  • 6,267
  • 6
  • 33
  • 47
Mohammad
  • 194
  • 5
  • 14
  • The key here to understand why what you tried didn't work is to understand that `parent[1]` is *not* the same as `child`. They are two separate objects who happen to both be arrays and who happen to have the same childs in turn. But JS doesn't know that. So you need to add logic that compares the parent's `[c, d]` with the child and determines that they are identical as far as you're concerned. –  Jan 25 '19 at 10:35
  • Marked this as a dupe because it is essentially: "I want to do `parent[1] == child`, how?" That fact that parent is also an array is irrelevant to the question. –  Jan 25 '19 at 10:42
  • @ChrisG As you suggested, the question is not about comparing. Its about *why includes fails*. So, I guess its not a dupe. However, I'll add it to my answer as reference – Rajesh Jan 25 '19 at 10:52
  • @Rajesh `includes()` is based on comparisons though, and OP therefore implicitly assumes that `parent[1] == child` should evaluate to `true`. The duplicate explains why that's not the case and shows a solution. It's a perfect dupe, in other words. –  Jan 25 '19 at 10:55

2 Answers2

2

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);
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • 4
    IMO any answer to this question must address why `includes()` fails. This is a question where it is important to understand *why* one has to tackle the issue like this. Edit: I downvoted this, because it will regard the two as identical even if child has additional elements. –  Jan 25 '19 at 10:38
1

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.

References:

Community
  • 1
  • 1
Rajesh
  • 24,354
  • 5
  • 48
  • 79