- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- Get the item that appears the most times in an array JavaScript
- How to find the one integer that appears an odd number of times in a JavaScript array?
- Get count of how many times a string appears in a MySQL column?
- Program to find how many times a character appears in a string in PHP
- Counting unique elements in an array in JavaScript
- Take an array and find the one element that appears an odd number of times in JavaScript
- Counting possible APs within an array in JavaScript
- Count how many times the substring appears in the larger String in Java
- How to append an item into a JavaScript array?
- Number of times a string appears in another JavaScript
- How can I remove a specific item from an array in JavaScript
- First element that appears even number of times in an array in C++
- Counting number of triangle sides in an array in JavaScript
- Single dimensional array vs multidimensional array in JavaScript.
- How can I remove a specific item from an array JavaScript?

Advertisements