Search code examples
javascriptarraysloopsfrequency

Push arrays to one array, then cycle through new array


I need to cycle through several arrays to find the out how often a particular value shows up.

I can pass the values to one new array, and this works, however when I try to loop through it it doesn't seem to work.

As this is for class, I cannot use jQuery - solely logic!!

var mon = ["Ez, Caro"];
var tue = ["Ez, Matt, Pablo"];
var wed = ["Marta"];
var thur = ["Ez, Matt"];
var freq = 0;
var arr = [];

var input = prompt ("Search a name");

arr.push(mon, tue, wed, thur);

for (var i = 0; i<arr.length; i++){
  if (arr[i] == input){

    freq = freq + 1;
  }

}
document.write("It appears " + freq + " time(s)")

Solution

  • Assuming that each array is supposed to have multiple strings instead of just one like in the question, you could do something like below with vanilla JavaScript. Check the comments for logic.

    var mon = ["Ez", "Caro"];
    var tue = ["Ez", "Matt", "Pablo"];
    var wed = ["Marta"];
    var thur = ["Ez", "Matt"];
    
    //combine your arrays for simplicity
    var arr = mon.concat(tue).concat(wed).concat(thur);
    
    //use an object as a map to keep track of count
    var map = {};
    for (let i = 0; i < arr.length; i++) {
      if (!map[arr[i]]) {
        map[arr[i]] = 1;
      } else {
        map[arr[i]] = map[arr[i]] + 1;
      }
    }
    
    //get the user input
    var input = prompt("Search a name");
    
    //store the count of requested input (case-sensitive)
    var countOfRequested = map[input] ? map[input] : 0;
    
    //display to the user
    console.log(input + ' appears ' + countOfRequested + ' times.');