I have an object containing arrays, I want to count the number of occurrences a particular string is found across all arrays in the object.
const festivals = {
'Danny': ['Glastonbury','Glastonbury','Leeds','Leeds','Leeds','Benicassim','MadCool'],
'Jimbo': ['Glastonbury','Glastonbury','Leeds','Leeds','Leeds','Leeds','Benicassim','MadCool'],
'Richard': ['Glastonbury','Leeds','Leeds','Benicassim','MadCool'],
'John': ['Glastonbury','Leeds']
}
let totalFestivals = 0
let target = 'Benicassim'
for (let festival in festivals){
if (festivals[festival] === target){
totalFestivals++
}
}
console.log (totalFestivals). //
2
Answers
maybe something like that?…
First, the == is not working because you are telling javascript this:
Example with Danny:
Instead you do this:
Details:
The includes function return true if the parameter is inside a list.
Problem:
But because of the way you write the function, your result will be max 4, because you have 4 list and your function and the includes do not count the occurrences.
Solution:
With the second for in the code below you will compare every index of the current list(example : ‘Danny’ list) with target and if they are equal the totalFestivals increase.