AngularJavaScript reduce方法可以用来寻找移动平均线吗

sgtfey8w  于 2023-03-28  发布在  Java
关注(0)|答案(2)|浏览(137)

我想转换我当前的Angular reduce函数,以计算基于每2-3个项目的移动平均线。这是否可以使用标准的Angular Reduce函数?
这是我目前必须计算的基本平均值,但如果可能的话,我想将其转换为可设置周期的移动平均值,但不确定如何/是否可以使用标准的Angular JS Reduce函数。

const data = [
    { val: 20 },
    { val: 15 },
    { val: 10 },
    { val: 12 },
    { val: 15 },
    { val: 09 },
    { val: 14 },
    { val: 17 },
    { val: 11 },
    { val: 15 }
]

var avg = data.reduce((accum, curVal) => accum + curVal.val, 0) / data.length;
console.log("avg= " + avg);
cgyqldqp

cgyqldqp1#

如果我对这个问题的理解是正确的,你需要一个数组,它包含一组基于窗口的平均值,该窗口在数据中一次移动一个条目。下面是一个使用for循环的例子,请参阅注解以了解其工作原理:

const data = [{ val: 20 }, { val: 15 }, { val: 10 }, { val: 12 }, { val: 15 }, { val: 9 }, { val: 14 }, { val: 17 }, { val: 11 }, { val: 15 }];

const get_moving_averages = (data, window_size = 3) => {
  const sums = [];
  
  for(let i = 0; i < data.length; i++) {
    if(i < window_size) {
      // add everything to the first slot for the first items up to window size
      sums[0] = (sums[0] ?? 0) + data[i];
    } else {
      // calculate value by taking the previous value, adding the new data
      // and taking off value that shouldn't be included in this sum from the previous sum
      sums[i + 1 - window_size] = sums[i - window_size] + data[i] - data[i - window_size];
    }
  }
  
  return sums.map((sum) => sum / window_size);
};

console.log(get_moving_averages(data.map(({val}) => val)));

同样的想法,但有一个reduce函数:

const data = [{ val: 20 }, { val: 15 }, { val: 10 }, { val: 12 }, { val: 15 }, { val: 9 }, { val: 14 }, { val: 17 }, { val: 11 }, { val: 15 }];

const get_moving_averages = (data, window_size = 3) =>
  data.reduce((acc, val, i, all) => {
    const first_few = i < window_size;
    const sum_index = first_few ? 0 : i + 1 - window_size;
    
    acc[sum_index] = (acc[sum_index] ?? 0) + val;
    
    if(!first_few)
      acc[sum_index] += acc[sum_index - 1] - all[i - window_size];
    
    return acc;
  }, [])
  .map( (sum) => sum / window_size );

console.log(get_moving_averages(data.map(({val}) => val)));
j1dl9f46

j1dl9f462#

可以使用slice函数获取数组的一部分

let startIndex = 2;
let endIndex = 5;
let length = endIndex - startIndex;
var avg= data.slice(startIndex , endIndex ).reduce((accum, curVal) => accum + curVal.val, 0) / length;
console.log("avg= " + avg);

相关问题