Search code examples
javascriptprototypejs

Determines which day of the week had the most number of people visiting the store with JS prototype


mostPopularDays function determines which day of the week had the most number of people visiting the pet store. If two or more days are tied for the highest amount of traffic, an array containing the days should be returned. If the input is null or an empty array, the function should return null. The input is an array of Weekday objects. This function should return a string containing the name of the most popular day of the week if there is only one most popular day, and an array containing the names of the most popular days if there are more than one that are most popular.

function Weekday (name, traffic) {
   this.name = name;
   this.traffic = traffic;}                                             
function mostPopularDays(week) {
   var sat = new Weekday('Saturday', 33);
   var sun = new Weekday('Sunday', 23);
   var mon = new Weekday('Monday', 8);
   var tue = new Weekday('Tuesday', 15);
   var wed = new Weekday('Wednesday', 5);
   var thu = new Weekday('Thursday', 18);
   var fri = new Weekday('Friday', 29);
   week = [sat , sun , mon , tue , wed , thu , fri];
   for (var i = 0 ; i <= length-1 ; i++){
      if(week[i].traffic > week[i+1].traffic)
         return week[i].name;}}

I write this function and it doesn't work. I am new in Javascript.


Solution

  • First, try to make your function more general so that it works on any array of days that is passed in. One approach to solve this is to sort the days by descending order and return the first element (or elements if there are multiple days with the same highest traffic).

    var sat = new Weekday('Saturday', 33);
    var sun = new Weekday('Sunday', 23);
    var mon = new Weekday('Monday', 8);
    var tue = new Weekday('Tuesday', 33);
    var wed = new Weekday('Wednesday', 5);
    var thu = new Weekday('Thursday', 18);
    var fri = new Weekday('Friday', 29);
    var week = [sat , sun , mon , tue , wed , thu , fri];
    
    function mostPopularDays(week) {   
       week.sort((a, b) => b.traffic - a.traffic); // sort by descending order
       return week
               .filter(day => day.traffic === week[0].traffic)
               .map(day => day.name);
    }
    
    console.log(mostPopularDays(week)); // [Saturday, Tuesday]
    

    As for your attempt, some problems with your for loop are:

    • length is not defined (you probably meant week.length)
    • You immediately return if you find a day at index i that has more traffic than the day at the next index. Think about the correctness of this approach (i can also go beyond the array, which is not desirable). You want to at least look at all days in the array and somehow determine which one has the most traffic.