Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
JavaScript array.includes inside nested array returning false where as searched name is in array
When working with nested arrays in JavaScript, the standard includes() method only checks the first level of the array. This article explores why this happens and provides a simple solution using JSON.stringify() to search through multidimensional arrays.
The Problem
The Array.prototype.includes() method only performs shallow comparison, meaning it cannot find elements nested within sub-arrays:
const names = ['Ram', 'Shyam', ['Laxman', 'Jay']];
console.log(names.includes('Ram')); // true - found at first level
console.log(names.includes('Laxman')); // false - nested inside sub-array
true false
Solution: Using JSON.stringify()
A simple approach is to convert the entire nested array to a JSON string and then use includes() to search within that string:
const names = ['Ram', 'Shyam', 'Laxman', [
'Jay', 'Jessica', [
'Vikram'
]
]];
const includesMultiDimension = (arr, str) =>
JSON.stringify(arr).includes(str);
console.log(includesMultiDimension(names, 'Vikram')); // true
console.log(includesMultiDimension(names, 'Ram')); // true
console.log(includesMultiDimension(names, 'NotFound')); // false
true true false
How It Works
The JSON.stringify() method converts the nested array into a flat string representation:
const nestedArray = ['a', ['b', 'c']];
const jsonString = JSON.stringify(nestedArray);
console.log(jsonString); // ["a",["b","c"]]
console.log(jsonString.includes('b')); // true
["a",["b","c"]] true
Limitations
This approach has some important limitations to consider:
const problematicArray = ['test', 'ing'];
// False positive: searches for 'tes' but finds it within 'test'
console.log(JSON.stringify(problematicArray).includes('tes')); // true
// Better approach: exact match with quotes
console.log(JSON.stringify(problematicArray).includes('"tes"')); // false
console.log(JSON.stringify(problematicArray).includes('"test"')); // true
true false true
Alternative: Using Array.flat()
For modern browsers, you can use Array.flat() to flatten the array completely:
const names = ['Ram', ['Shyam', ['Laxman']]];
// Flatten all levels and then use includes
console.log(names.flat(Infinity).includes('Laxman')); // true
true
Comparison
| Method | Pros | Cons |
|---|---|---|
JSON.stringify() |
Simple, works in all browsers | Potential false positives, string-only |
Array.flat() |
More accurate, handles all data types | Limited browser support |
Conclusion
The JSON.stringify() approach provides a simple one-line solution for searching nested arrays, though it's best suited for string searches. For more robust solutions, consider using Array.flat() or implementing recursive search functions.
