
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript Array Includes in Nested Array Returning False
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