'How to check if a list exist inside another list
So I have a list a that contain the string "ab" and another list b that contain a list that contain the string "ab". So it look something like this:
var a = ["ab"]
var b = [["ab"]]
How can I check if a is in b. I have try using b.includes(a) that result in a false and I also have try b.indexOf(a) which also return false. The way that I currently use is this:
var flag = false
var a = ["ab"]
var b = [["ab"]]
b.forEach((i) => {
if (i.join("") == a.join("")) flag = true
})
console.log(flag)
Is there like a shorter way?
Thanks y'all.
Solution 1:[1]
Not quiet sure what exactly you want to check but here are 2 examples:
var a = ["ab"];
var b = [["ab"]];
var flag = false;
//Example 1: search for "ab" in the nested array
b.forEach(el=>{
el.forEach(innerEl=>{
if(innerEl === "ab") flag = true;
});
});
console.log(`Result 1 ${flag}`);
//Example 1: seach for the exact array ["ab"]
b.forEach(el=>{
if(el == a)flag = true;
});
console.log(`Result 2 ${flag}`);
Solution 2:[2]
If you have references you can do as follows:
var a = ["ab"];
var b = [a];
b.includes(a); // true
Otherwise you need to convert those arrays to strings and compare those as others suggested or compare inside values of those nested arrays one by one because:
['a'] != ['a'] // this is true because those are 2 different arrays
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharman |
| Solution 2 |
