从给定数组获取属性的最大值

时间:2019-01-07 10:40:27

标签: javascript arrays object

/**
 * A prototype to create Weekday objects
 */


  function Weekday (name, traffic) {
        this.name = name;
        this.traffic = traffic;
    }
//function to return the day that has the most traffic.
function mostPopularDays(week) {
    // IMPLEMENT THIS FUNCTION!

}
//this is my input
var a = new Weekday('mon',123); var b = new Weekday('tues', 134) ; var c = new Weekday('wed', 233);
empty_me = []; 
empty_me.push(a ,b ,c);
mostPopularDays(empty_me);
// it should return the day with most traffic
//e.g wed

此代码将输入收集为数组,并在其中嵌入对象...函数“ mostPopularDays”应返回流量最大的日期名称的字符串或数组最大的日期名称的数组交通。

4 个答案:

答案 0 :(得分:0)

您可以使用reduce数组方法执行此操作:

function mostPopularDays(week) {
    let mostTrafficInADay = week.reduce((acc, val) => {
        acc = ( val.traffic > acc ) ? val.traffic : acc;
        return acc;
    }, 0);
    return week.filter(day => day.traffic === mostTrafficInADay).map(day => day.name);
}

这将返回一个数组,其中包含流量最高的日子的所有名称的字符串。

编辑:由于问题已更改,因此它也使用数组mapfilter方法。

答案 1 :(得分:0)

有点长,但是 首先,您可以找到最大值,然后在列表匹配中找到相关项目

var wdArr = [ {name: "mon", traffic: 123}, {name: "tue", traffic: 120}, {name: "wed", traffic: 124}, {name: "thurs", traffic: 455}]



resInt = Math.max.apply(Math, wdArr.map(function(o) { return o.traffic; }))

resObj = wdArr.filter (function(el){

return el.traffic == resInt
});

console.log(resObj)

答案 2 :(得分:0)

您可以比较array#redcue中的点击量值并获取高度值为traffic的对象。

let data = [{name: "mon", traffic: 123}, {name: "tue", traffic: 120}, {name: "wed", traffic: 124}, {name: "thurs", traffic: 455}],
    result = data.reduce((r,o) => r.traffic < o.traffic ? o : r);
console.log(result);

答案 3 :(得分:0)

您可以使用reduce() method

  

reduce()方法在数组的每个成员上执行reducer函数(由您提供),从而产生单个输出值。

var weekdays = [
  {name: "mon", traffic: 123},
  {name: "tue", traffic: 120}, 
  {name: "wed", traffic: 124}, 
  {name: "thu", traffic: 455},
  {name: "fri", traffic: 455},
]


var maxTrafficWeekday = weekdays.reduce(function (acc, val) {
  return val.traffic > acc.traffic ? val : acc
})

console.log(maxTrafficWeekday)

上面的代码将返回流量最多的第一天。如果您想获得流量最多的最后一天,可以更改算法:

var weekdays = [
  {name: "mon", traffic: 123},
  {name: "tue", traffic: 120}, 
  {name: "wed", traffic: 124}, 
  {name: "thu", traffic: 455},
  {name: "fri", traffic: 455},
]


var maxTrafficWeekday = weekdays.reduce(function (acc, val) {
  return val.traffic >= acc.traffic ? val : acc
  // -----------------^
})

console.log(maxTrafficWeekday)