Skip to content

Find the total occurrences of an element in a JavaScript multidimensional array

Advertisements

Given a multidimensional array in JavaScript, we need to find the count of occurrences of an element in the array.

var words = [
   ["one", "two", "three"],
   ["nine", "one", "four"],
   ["six", "two", "eight"],
   ["seven", "five", "ten"],
];



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(words, "two")); //2

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.