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

时间:2017-01-25 11:48:17

标签: 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会显示出来 数字1,前3个元素的平均值 数字2,平均第二个3个元素 3号 等等

你能帮帮我吗?

9 个答案:

答案 0 :(得分:2)

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

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]

&#13;
&#13;
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)
); 
&#13;
&#13;
&#13;

如果您想获得平均值的舍入值,可以使用上面的代码,但修改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)
);

&#13;
&#13;
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)
);
&#13;
&#13;
&#13;

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

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)
);

&#13;
&#13;
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)
);
&#13;
&#13;
&#13;

参考文献:

答案 1 :(得分:1)

一般方法是接受数组和批量大小,并根据大小,计算批次总数,并按大小除以总和得到平均值。

&#13;
&#13;
function groupAverage(arr, n) {
  var result = [];
  for (var i = 0; i < arr.length;) {
    var sum = 0;
    for(var j = 0; j< n; j++){
      // Check if value is numeric. If not use default value as 0
      sum += +arr[i++] || 0
    }
    result.push(sum/n);
  }
  return result
}

var arr = [1, 3, 2, 1, 5, 6, 7, 89,"test", 2, 3, 6, 8];

console.log(groupAverage(arr, 3))
console.log(groupAverage(arr, 2))
&#13;
&#13;
&#13;

答案 2 :(得分:1)

试试这个

var arr = [1, 2, 3, 4, 5, 6];
var avgs = [];
sum = 0;
for (var i = 0; i < arr.length; i++) {
  sum = sum + arr[i];
  if ((i + 1) % 3 == 0) {
    avgs.push(sum / 3);
    sum = 0;
  }
}
console.log(avgs);

答案 3 :(得分:0)

您可以创建一个计数器变量并在每次迭代时递增它。

var counter;

for ...
conuter++;
if(counter % 3 === 0)
  // make some staff

答案 4 :(得分:0)

您可以使用reduce()map()来执行此操作。

&#13;
&#13;
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var c = 0

var avg = arr.reduce(function(r, e, i) {
  if(i % 3 == 0) c++
  r[c] = (r[c] || 0) + e / 3
  if(i == arr.length - 1) r = Object.keys(r).map(e => r[e])
  return r;
}, {})

console.log(avg)
&#13;
&#13;
&#13;

答案 5 :(得分:0)

您可以先添加值,如果它有正确的计数,则取平均值。

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
    nth = 3,
    avg = array.reduce(function (r, a, i) {
        var ii = Math.floor(i / nth);
        r[ii] = ((r[ii] || 0) + a) / (i % nth !== nth - 1 || nth);
        return r;
    }, []);

console.log(avg);

答案 6 :(得分:0)

我不会发布代码段,但会尝试解释他们的代码背后的推理。 一种可能的解决方案是仅在3次迭代后添加平均值。他们通过使用计数器并测试计数器模3来实现它:

if (counter % 3 == 0) {your code calc the average}

如果计数器模3 = 0,那么可以将其分为3:如果计数器可以被3分割,则执行操作。

答案 7 :(得分:0)

如何使用for循环,而是每次递增3并将平均值推送到avgArray列表

喜欢这个

var avgArray = []
for(i=0; i < arr.length; i+=3) { 
    total = arr[i] + (arr[i+1] || 0)+ (arr[i+2] || 0) ;
    avg = total/3 ;
    avgArray.push(Math.round(avg) );}

答案 8 :(得分:0)

这是一种尾调用递归方法,仅适用于某些类型;

&#13;
&#13;
var         arr = Array(20).fill().map(_=> ~~(Math.random()*20)),
averageByGroups = (a,n,i=0,r=[]) => a.length-i > 0 ? averageByGroups(a,n,i+n,r.concat(a.slice(i,n+i).reduce((p,c,_,s) => p+c/s.length,0))) : r;
console.log(JSON.stringify(arr));
console.log(JSON.stringify(averageByGroups(arr,3)));
&#13;
&#13;
&#13;