I'm trying to get familiar with arrow functions and in this case the ability to count the number of occurrences of a string within a 2D array. This is what I have so far:
GOAL Count the number of occurrences of 'cat' in a 2D array
Array
var arr = [ ['mammal','dog','fur'], ['mammal','cat','fur'], ['mammal','cat','fur'], ['fish','trout','scales'] ];
Current code using forEach
var count = arr.map(outer => outer.forEach(str => {
if(str == 'cat') {
count + 1;}
}));
return console.log(count.length);
ACTUAL RESULT
Info 4
DESIRED RESULT
Info 2
As I mentioned, I'm still new to custom functions so any help would be sincerely appreciated.
Here are some.. more efficient solutions.
.map()
isn't necessarily the strongest Array Method to use here, as we don't need to clone and modify the original array as we iterate through the data. We're just looking counting occurances.
Using .reduce()
:
const count = arr.reduce((acc, row) => {
row.forEach((item) => {
if (item === `cat`) acc++
})
return acc
}, 0)
Using .flatMap()
and .filter()
:
const count = arr.flatMap((row) => row).filter((item) => item === `cat`).length
Learn More: