array.includes returning false where as searched name is in array

Viewed 68

If var c = familyArray.includes("Bart"); it will return false but if var c = familyArray.includes("Homer"); it will return true

I want it to be true in the case of Bart as well because it is also included in the array.

Below is my array:

var familyArray = ["Marge", "Homer", ["Bart", "Lisa", "Maggie"]];
var a = familyArray.indexOf("Bart");
var b = familyArray[2][0];
var c = familyArray.includes("Bart");

document.getElementById("demo").innerHTML = c;

console.log(a);
console.log(b);
<p id="demo"></p>

5 Answers

Your issue is that you have a multi-dimensional array, and array includes will not search the inner array. Thus, you need to flatten your array before searching it. Here I have used Infinity as a parameter in the case that your array has more dimensions than just 2:

var familyArray = ["Marge", "Homer", ["Bart", "Lisa", "Maggie"]];
var c = familyArray.flat(Infinity).includes("Bart");

console.log(c); // true;

See browser support for .flat() here. If you need better browser support you can use an alternative approach found here

You are using nested arrays, you can use .flat before hand:

familyArray.flat().includes('Bart')

You are searching in the inner array. You can do like this.

var familyArray = ["Marge", "Homer", ["Bart", "Lisa", "Maggie"]];

console.log(familyArray[2].includes("Bart"));

you can do this :

var c = familyArray.flat(1).includes("Bart");

try flat method for this

var familyArray = ["Marge", "Homer", ["Bart", "Lisa", "Maggie"]];
var familyArrayFlatten = familyArray.flat();
var a = familyArrayFlatten.indexOf("Bart");
var b = familyArrayFlatten[2][0];
var c = familyArrayFlatten.includes("Bart");



console.log(a);
console.log(b);
console.log(c);

Related