Skip to content
Advertisement

How to get the number of word occurrences in a 2D array?

I’ve found a solution that gives the correct result when the word is at the same index, within each of the array elements, but in the case below, the term/word searched can be anywhere in the element (beginning or end).

JavaScript

Expected result:

JavaScript

Here’s the attempt using the solution above:

JavaScript

Appreciate your help!

Advertisement

Answer

So: basically the same as Louys Patrice Bessette’s answer but instead of setting the value of the object prop to the current count it assigns an array (word and count) to the value instead, and then updates the count at index 1. Wrapping the operation in Object.values will return only those arrays (as an array).

JavaScript

Additional documentation

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement