Problem to return high value of the function in javascript [closed]

-2

I'm trying to make a function that returns the highest value of the attribute of an object within an array, always return the initial value of the variable that I output in my function, please any suggestions. Thank you

var lunes = new Weekday("lunes", 5);
var martes = new Weekday("martes", 5);
var miercoles = new Weekday("miercoles", 15);
var jueves = new Weekday("jueves", 30);
var viernes = new Weekday("viernes", 50);

var week = [lunes,martes,miercoles,jueves,viernes] ;

var result = mostPopularDays(week);
console.log(result);

function Weekday (name, traffic) {
    this.name = name;
    this.traffic = traffic;
}

 function mostPopularDays(week) {
		var masPublico = 0;
		
		for(var i=0; i <= week[i] ; i++){
			if(week[i].traffic < masPublico ){
				masPublico = week[i].traffic;
			}
		}
		return masPublico;  
}
    
asked by user3821102 12.12.2017 в 23:53
source

1 answer

-1

Ready friend and solve with your example the only thing is to change the comparison of place of this

 if(week[i].traffic <  masPublico){
        masPublico = week[i].traffic;
    }

to this

if(masPublico <  week[i].traffic){
        masPublico = week[i].traffic;
    }

You also have to change the for that to iterate an object you have to pass the total bone objeto.length why the for does not work I hope it works

To obtain the day we do a filter() of the array and we return nothing but the object whose traffic equals the largest.

var lunes = new Weekday("lunes", 5);

 var martes = new Weekday("martes", 5);

 var miercoles = new Weekday("miercoles", 15);

 var jueves = new Weekday("jueves", 30);

 var viernes = new Weekday("viernes", 50);

 var week = [lunes,martes,miercoles,jueves,viernes] ;

 mostPopularDays(week);

  function Weekday (name, traffic) {

this.name = name;

this.traffic = traffic;

}
   function mostPopularDays(week) {
   
    var masPublico = 0;

    for(var i=0; i < week.length ; i++){
    
        if(masPublico <  week[i].traffic){
            masPublico = week[i].traffic;
        }
    }
    var dia = week.filter((item)=>{
      return item.traffic == masPublico
    })

    console.log(dia[0].name,masPublico)
    return masPublico;  
}

Here is an example of how to get the highest value of a array I hope you help

The idea is to iterate the arrangement and compare the value with the maximum that is added by finding one greater than the previous one.

var values = [5,10,25,8,12],
    max = 0;

for(var i=0,len=values.length;i<len;i++){
    if(max < values[i]){
        max = values[i];
    }
}
console.log(max)
    
answered by 12.12.2017 / 23:59
source