Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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>
like image 829
user2828442 Avatar asked Dec 29 '25 14:12

user2828442


2 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

like image 109
Nick Parsons Avatar answered Jan 01 '26 03:01

Nick Parsons


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

familyArray.flat().includes('Bart')
like image 21
kigiri Avatar answered Jan 01 '26 03:01

kigiri