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