相邻元素平均数数组 - JavaScript


假设我们有一个数字数组 -

const arr = [3, 5, 7, 8, 3, 5, 7, 4, 2, 8, 4, 2, 1];

我们需要编写一个函数,返回一个数组,其中包含相应元素及其前一个元素的平均值。对于第一个元素,如果没有前一个元素,那么应返回这个元素本身。

让我们编写此函数的代码,我们将使用 Array.prototype.map() 方法来解决此问题 -

示例

const arr = [3, 5, 7, 8, 3, 5, 7, 4, 2, 8, 4, 2, 1];
const consecutiveAverage = arr => {
   return arr.map((el, ind, array) => {
      const first = (array[ind-1] || 0);
      const second = (1 + !!ind);
      return ((el + first) / second);
   });
};
console.log(consecutiveAverage(arr));

输出

这将在控制台生成以下输出 -

[
   3,   4, 6, 7.5, 5.5, 4,
   6, 5.5, 3,   5,   6, 3,
   1.5
]

上次更新: 18-Sep-2020

237 次浏览

提升你的 职业

完成课程,获得证书

开始
广告
© . All rights reserved.