繁体   English   中英

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

[英]Get average of every group of n elements in an array

我有一个数字数组。 我想遍历该数组并计算每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等

你能帮我么 ?

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

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

参考文献:

一种通用方法是接受数组和批次大小,然后根据大小,计算批次总数并将总和除以大小以得出平均值。

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

尝试这个

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

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

var counter;

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

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

 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) 

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

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

我不会发布代码片段,而是尝试在代码背后解释其原因。 一种可能的解决方案是仅在3次迭代后添加平均值。 他们通过使用计数器并以模3的方式测试计数器来做到这一点:

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

如果计数器的模数为3 = 0,则可被3整除,这类似于:如果计数器可被3整除,请执行操作。

如何使用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) );}

这是一种尾随递归方法,仅适用于某些变化。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM