可以使用Array.prototype方法完成此功能

时间:2017-09-01 18:03:55

标签: javascript arrays array.prototype.map

我试图采用新的Array.prototype函数,并想知道如何使用它完成此代码。

目标是,将每12个对象的平均值作为数组从原始对象数组返回。

{{1}}

小提琴:std::vector

3 个答案:

答案 0 :(得分:0)

Array.prototype.getAverageWeather = function() {
    var AverageWeather = []; 
    var temp = 0;

    for (i = 0; i < this.length; i++) {

        temp += this[i].t;
        if ((i+1) % 12 == 0) {
      AverageWeather.push( Math.round((temp / 12) * 100) / 100 );
        Temp = 0;
        }
    }

    return AverageWeather;
}

var WeatherData = [{tm:0,t:22,h:15,p:537},{tm:5,t:13,h:42,p:895},{tm:10,t:21,h:36,p:582},{tm:15,t:22,h:51,p:986},{tm:20,t:21,h:36,p:902},{tm:25,t:22,h:58,p:439},{tm:30,t:16,h:57,p:1042},{tm:35,t:20,h:14,p:480},{tm:40,t:20,h:34,p:958},{tm:45,t:17,h:7,p:403},{tm:50,t:13,h:69,p:460},{tm:55,t:20,h:36,p:967},{tm:60,t:19,h:57,p:419},{tm:65,t:18,h:43,p:746},{tm:70,t:17,h:49,p:344},{tm:75,t:16,h:90,p:651},{tm:80,t:19,h:96,p:646},{tm:85,t:19,h:3,p:301},{tm:90,t:14,h:96,p:770},{tm:95,t:17,h:54,p:1036},{tm:100,t:15,h:79,p:890},{tm:105,t:22,h:32,p:1041},{tm:110,t:22,h:67,p:415},{tm:115,t:20,h:82,p:616}];

console.log(WeatherData.getAverageWeather());

这样您可以将函数附加到Array原型。

答案 1 :(得分:0)

您可以将reduce和map结合使用

 let averages = WeatherData
 .reduce(groupInto12, [])
 .map(getAverage);

function groupInto12(rows, key, index){
    if(index % 12 === 0)
       rows.push([key])
    else
       rows[rows.length-1].push(key)
       return rows;
}
function getAverage (tempfor12days) {
  let totalTemp = tempfor12days.reduce((acc,val)=>acc+val.t,0);
  return Math.round((totalTemp / 12) * 100) / 100;
 }

答案 2 :(得分:0)

当您在尝试计算平均值之前将数据拆分为12个组时,使用Array.prototype方法map reduce等更容易解决这个问题:

var weatherData = [{tm:0,t:22,h:15,p:537},{tm:5,t:13,h:42,p:895},{tm:10,t:21,h:36,p:582},{tm:15,t:22,h:51,p:986},{tm:20,t:21,h:36,p:902},{tm:25,t:22,h:58,p:439},{tm:30,t:16,h:57,p:1042},{tm:35,t:20,h:14,p:480},{tm:40,t:20,h:34,p:958},{tm:45,t:17,h:7,p:403},{tm:50,t:13,h:69,p:460},{tm:55,t:20,h:36,p:967},{tm:60,t:19,h:57,p:419},{tm:65,t:18,h:43,p:746},{tm:70,t:17,h:49,p:344},{tm:75,t:16,h:90,p:651},{tm:80,t:19,h:96,p:646},{tm:85,t:19,h:3,p:301},{tm:90,t:14,h:96,p:770},{tm:95,t:17,h:54,p:1036},{tm:100,t:15,h:79,p:890},{tm:105,t:22,h:32,p:1041},{tm:110,t:22,h:67,p:415},{tm:115,t:20,h:82,p:616}];

var groups = [];

while(weatherData.length) {
    groups.push(weatherData.splice(0, 12));
}

var averageWeather = groups.map(function(g) {
    return Math.round((g.reduce(function(acc, val) { 
       return acc + val.t
    }, 0) / 12) * 100) / 100;
});

console.log(averageWeather);