JavaScript array.includes inside nested array returning false where as searched name is in array


It is a well-known dilemma that when we use includes() inside nested arrays i.e., multidimensional array, it does not work, there exists a Array.prototype.flat() function which flats the array and then searches through but it’s browser support is not very good yet.

So our job is to create a includesMultiDimension() function that takes in an array and a string and returns a boolean based on the presence/absence of that string in the array.

There exist many solutions to this problem, most of them includes recursion, heavy array function, loops and what not.

What we are going to discuss here is by far the easiest way to check for presence/absence of string in nested arrays.

The code for this is −

Example

const names = ['Ram', 'Shyam', 'Laxman', [
   'Jay', 'Jessica', [
      'Vikram'
   ]
]];
const includesMultiDimension = (arr, str) =>
JSON.stringify(arr).includes(str);
console.log(includesMultiDimension(names, 'Vikram'));

This one line solution includes converting the array into a JSON string so that we can simply apply includes to it.

Output

The console output will be −

True

Updated on: 18-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements