skip to Main Content

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


  1. maybe something like that?…

    for (let festival in festivals) {
      const festivalArray = festivals[festival];
      for (let i = 0; i < festivalArray.length; i++) {
        if (festivalArray[i] === target) {
          totalFestivals++;
        }
      }
    }
    
    Login or Signup to reply.
  2. First, the == is not working because you are telling javascript this:

    Example with Danny:

        if(['Glastonbury','Glastonbury','Leeds','Leeds','Leeds','Benicassim','MadCool'] == 'Benicassim'){
            ...
        }
    

    Instead you do this:

    festivals[festival].includes(target)
    

    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.

    for (let festival in festivals){
        for(var i = 0; i < festivals[festival].length; i++){
            if (festivals[festival][i] === target){
                totalFestivals++
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search