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

JavascriptWeb DevelopmentObject Oriented Programming

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 −


const names = ['Ram', 'Shyam', 'Laxman', [
   'Jay', 'Jessica', [
const includesMultiDimension = (arr, 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.


The console output will be −

Published on 18-Aug-2020 07:43:11