Count number of occurrences in an array

Count number of occurrences in an array
0

#1

I have an array and need to count the number of occurrences of 3 values in it.

BOWL = [“jelly-bean”, “m&m”, “m&m”,“chocolate”, “m&m”, “jelly-bean”, “m&m”, “m&m”, “jelly-bean”];

How do I write the function that will tell me the numbers of occurrences of all 3 values?
I managed to do so only for 1 value but do not know how to do it for 3 values at the same time…


var BOWL = ["jelly-bean", "m&m", "m&m",
"chocolate", "m&m", "jelly-bean", "m&m", "m&m", "jelly-bean"];

var jbOccur = 0; //for "jelly-bean"
var mOccur = 0; //for "m&m"
var chocOccur = 0; //for "chocolate"

jbOccur = Occurrence(BOWL); //calling the function, sending the BOWL array
console.log (jbOccur);

//Define the function
function Occurrence(arr){
   var CountjbOccur=0
  for(var i=0;i<arr.length;i++){
    if(arr[i]=="jelly-bean"){
    CountjbOccur++;
    }
    }
return CountjbOccur
  
}

#2

using regex will make it easier to use and modify, like this


#3

Thanks.
What if I want it in an old fashion way, similar to what I started?


#4

You did not specify the format you wanted to return from the function, so I went with something similar to what @alta9 returned.

function Occurrence(arr){
  var jbOccur = 0; //for "jelly-bean"
  var mOccur = 0; //for "m&m"
  var chocOccur = 0; //for "chocolate"
  for(var i=0; i<arr.length; i++){
    switch(arr[i]) {
    case "jelly-belly":
      jbOccur++;
      break;
    case "m&m":
      mOccur++;
      break;
    case "chocolate":
       chocOccur++;
       break;
    }
  }
  return "jelly-bean = " + jbOccur + ", m&m =" + mOccur + ", chocolate = " + chocOccur;
}

If you only cared about displaying items with quantities of 1 or more, then there is a much better solution which could be used to count the quantities for a million different types of candy items in the array.


#5

Hi,
many thanks, appriciate the effort