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
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 < arr.length; i++){
if(arr[i] === query){
count++;
continue;
};
if(Array.isArray(arr[i])){
count += calculateCount(arr[i], query);
}
};
return count;
};
console.log(calculateCount(arr, "apple"));
Output
The output in the console will be −
7
Advertisements
