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>
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With