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
Selected Reading
Counting how many times an item appears in a multidimensional array in JavaScript
We have a nested array of strings and we have to write a function that accepts the array and a search string and returns the count of the number of times that string appears in the nested array.
Therefore, let's write the code for this, we will use recursion here to search inside of the nested array and the code for this will be ?
Example
const arr = [
"apple",
["banana", "strawberry","dsffsd", "apple"],
"banana",
["sdfdsf","apple",["apple",["nonapple", "apple",["apple"]]]]
,"apple"];
const calculateCount = (arr, query) => {
let count = 0;
for(let i = 0; i
Output
The output in the console will be ?
7
How It Works
The function uses recursion to traverse the multidimensional array:
- For each element, check if it matches the search query
- If it's a match, increment the counter
- If the element is itself an array, recursively call the function on that sub-array
- Add the results from nested arrays to the main counter
Alternative Using Array.flat()
For simpler cases, you can flatten the array first:
const countWithFlat = (arr, query) => {
return arr.flat(Infinity).filter(item => item === query).length;
};
console.log(countWithFlat(arr, "apple"));
7
Comparison
| Method | Memory Usage | Performance | Readability |
|---|---|---|---|
| Recursive | Lower | Better for large arrays | More complex |
| Array.flat() | Higher | Creates new array | More readable |
Conclusion
The recursive approach efficiently counts occurrences in multidimensional arrays without creating additional arrays. Use Array.flat() for simpler cases where memory isn't a concern.
Advertisements
