Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to use forEach to count occurrences in 2D array

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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:

Array Methods

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading