Home > Mobile >  How to check if a list exist inside another list
How to check if a list exist inside another list

Time:02-13

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.

CodePudding user response:

Little trick for you. You can compare two array if you use toString() method.

const a = ["ab"];
const b = [["ab"]];
const result = b.some(p => p.toString().includes(a));

console.log(result);

CodePudding user response:

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}`);

CodePudding user response:

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
  • Related