javascript - 获取数组中每组 n 个元素的平均值

标签 javascript arrays

我有一个数字数组。 我想遍历该数组并计算每 3 个元素的平均值并将这些平均值存储在一个新数组中。

这是我的代码

         var total = 0;
          //my array with the numbers in
         for(i=0; i < arr.length; i++)
             {
                  total += arr[i];
             }

            var avg = total / arr.length;
            avgArray.push(Math.round(avg));

使用这段代码,我只能得到所有数组元素的平均值。 我需要每 3 个元素制作一次。所以 avgArray 会显示 number1,前 3 个元素的平均值 数字 2,后 3 个元素的平均值 3号 等等

你能帮帮我吗?

最佳答案

一种可能的方法,使用功能性方法(而不是程序性方法):

function averageEvery(arr, n) {
  // if we have neither an arr, or an n
  // variable we quit here:
  if (!arr || !n){
    return false;
  }

  // creating an variable by the name of 'groups'
  // using an array-literal:
  let groups = [];

  // while the supplied Array ('arr') still
  // has a non-zero length:
  while (arr.length) {

    // we remove the first elements of that
    // Array from the index of 0 to the
    // index supplied in the variable 'n':
    groups.push(arr.splice(0, n));
  }

  // here we return the Array of averages, created
  // using Array.prototype.map() to iterate over
  // the Arrays held in the groups Array:
  return groups.map(

    // here we use Arrow functions, 'group'
    // is a reference to the current Array-
    // element, the Array from the Array of
    // Arrays over which we're iterating:
    group =>

    // here we use Array.prototype.reduce()
    // to sum the values of the Array:
    group.reduce(

      // 'a' : the accumulated value returned
      // from the last iteration;
      // 'b' : the current number of the Array
      // of Numbers over which we're iterating:
      (a, b) => a + b

    // once we find the sum, we then divide that
    // sum by the number of Array-elements to find
    // the average:
    ) / group.length
  );

}

console.log(
  averageEvery([1, 2, 3, 4, 5, 6], 3)
); // [2, 5]

function averageEvery(arr, n) {
  if (!arr || !n) {
    return false;
  }
  let groups = [];
  while (arr.length) {
    groups.push(arr.splice(0, n));
  }

  return groups.map(
    group =>
    group.reduce(
      (a, b) => a + b
    ) / group.length
  );

}

console.log(
  averageEvery([1, 2, 3, 4, 5, 6], 3)
); 

如果你想获得平均值的舍入值,你可以使用上面的代码,但要修改 console.log() 语句:

console.log(

  // here we use Array.prototype.map() to modify the returned
  // Array, with Math.round() as the callback function; this
  // callback function receives three arguments:
  // array-element: the average number,
  // array-element index: the index of that number in the Array,
  // array-copy: a copy of the whole Array
  // Math.round() takes only one argument (the rest are simply
  // discarded), the array-element, and rounds that array-element
  // the rounded number is then returned by Array.prototype.map()
  // create a new Array of the rounded averages:
  averageEvery([1, 2, 4, 5, 6, 7], 3).map(Math.round)
);

function averageEvery(arr, n) {
  if (!arr || !n){
    return false;
  }
  let groups = [];
  while (arr.length) {
    groups.push(arr.splice(0, n));
  }

  return groups.map(
    group =>
    group.reduce(
      (a, b) => a + b
    ) / group.length
  );

}

console.log(
  averageEvery([1, 2, 4, 5, 6, 7], 3).map(Math.round)
);

或者可以修改上述函数以返回函数形成要返回的平均值时的舍入平均值:

function averageEvery(arr, n) {
  if (!arr || !n) {
    return false;
  }
  let groups = [];
  while (arr.length) {
    groups.push(arr.splice(0, n));
  }

  return groups.map(
    group =>

    // here we use Math.round() to round
    // the calculated number:
    Math.round(group.reduce(
      (a, b) => a + b
    ) / group.length)
  );

}

console.log(
  averageEvery([1, 2, 4, 5, 6, 7], 3)
);

function averageEvery(arr, n) {
  if (!arr || !n) {
    return false;
  }
  let groups = [];
  while (arr.length) {
    groups.push(arr.splice(0, n));
  }

  return groups.map(
    group =>
    Math.round(group.reduce(
      (a, b) => a + b
    ) / group.length)
  );

}

console.log(
  averageEvery([1, 2, 4, 5, 6, 7], 3)
);

引用资料:

关于javascript - 获取数组中每组 n 个元素的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41850864/

相关文章:

javascript - 如果 $count 变量的值为零则隐藏列表元素

c++ - 为什么进程返回-1?

javascript - 在 Jquery 中读取分配给 Data- 的数组时出错。我正在使用 .data()

javascript - Laravel-MIX:合并/合并后删除未使用的文件

javascript - JS 用++ 添加变量在回调函数中不起作用

c++ - 如何在 C++ 中对数组中的字母进行排序?

java - 在 Java 中声明数组及其名称的不同方式

python - netCDF 文件中的 numpy 数组中的值无效(打印为 '--' )

Javascript:带有 for 循环的递归函数

javascript - 当我将脚本元素放在头部以从 URL 加载它时,我的 Javascript 不起作用