简体   繁体   English

如何计算数组中元素的总和和平均值?

[英]How to compute the sum and average of elements in an array?

I am having problems adding all the elements of an array as well as averaging them out.我在添加数组的所有元素以及平均它们时遇到问题。 How would I do this and implement it with the code I currently have?我将如何做到这一点并使用我目前拥有的代码来实现它? The elements are supposed to be defined as I have it below.这些元素应该按照我在下面的定义进行定义。

<script type="text/javascript">
//<![CDATA[

var i;
var elmt = new Array();

elmt[0] = "0";
elmt[1] = "1";
elmt[2] = "2";
elmt[3] = "3";
elmt[4] = "4";
elmt[5] = "7";
elmt[6] = "8";
elmt[7] = "9";
elmt[8] = "10";
elmt[9] = "11";

// Problem here
for (i = 9; i < 10; i++){
  document.write("The sum of all the elements is: " + /* Problem here */ + " The average of all the elements is: " + /* Problem here */ + "<br/>");
}   

//]]>
</script>

A solution I consider more elegant:我认为更优雅的解决方案:

const sum = times.reduce((a, b) => a + b, 0);
const avg = (sum / times.length) || 0;

console.log(`The sum is: ${sum}. The average is: ${avg}.`);
var sum = 0;
for( var i = 0; i < elmt.length; i++ ){
    sum += parseInt( elmt[i], 10 ); //don't forget to add the base
}

var avg = sum/elmt.length;

document.write( "The sum of all the elements is: " + sum + " The average is: " + avg );

Just iterate through the array, since your values are strings, they have to be converted to an integer first.只需遍历数组,因为您的值是字符串,所以必须先将它们转换为整数。 And average is just the sum of values divided by the number of values.平均值只是值的总和除以值的数量。

ES6 ES6

 const average = arr => arr.reduce( ( p, c ) => p + c, 0 ) / arr.length; const result = average( [ 4, 4, 5, 6, 6 ] ); // 5 console.log(result);

Calculating average (mean) using reduce<\/a> and ES6:使用reduce<\/a>和 ES6 计算平均值(mean):

const average = list => list.reduce((prev, curr) => prev + curr) / list.length;

const list = [0, 10, 20, 30]
average(list) // 15

generally average using one-liner reduce is like this一般平均使用单线减少是这样的

elements.reduce(function(sum, a,i,ar) { sum += a;  return i==ar.length-1?(ar.length==0?0:sum/ar.length):sum},0);

Average Shortest One Liner:<\/strong>平均最短一条线:<\/strong>

let avg = [1,2,3].reduce((a,v,i)=>(a*i+v)/(i+1));

Let's imagine we have an array of integers like this:假设我们有一个这样的整数数组:

var values = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

You can also use lodash , _.sum(array) and _.mean(array) in Math part (also have other convenient stuff).您还可以在数学部分使用lodash 、 _.sum(array) 和 _.mean(array) (还有其他方便的东西)。

_.sum([4, 2, 8, 6]);
// => 20
_.mean([4, 2, 8, 6]);
// => 5

不是最快的,但最短的一行是使用 map() 和 reduce():

var average = [7,14,21].map(function(x,i,arr){return x/arr.length}).reduce(function(a,b){return a + b})

I use these methods in my personal library:我在我的个人库中使用这些方法:

Array.prototype.sum = Array.prototype.sum || function() {
  return this.reduce(function(sum, a) { return sum + Number(a) }, 0);
}

Array.prototype.average = Array.prototype.average || function() {
  return this.sum() / (this.length || 1);
}

EDIT: To use them, simply ask the array for its sum or average, like:编辑:要使用它们,只需询问数组的总和或平均值,例如:

[1,2,3].sum() // = 6
[1,2,3].average() // = 2

In ES6-ready<\/strong> browsers this polyfill may be helpful.支持 ES6 的<\/strong>浏览器中,这个 polyfill 可能会有所帮助。

Math.sum = (...a) => Array.prototype.reduce.call(a,(a,b) => a+b)

Math.avg = (...a) => this.sum(...a)/a.length;

One sneaky way you could do it although it does require the use of (the much hated) eval().尽管确实需要使用(非常讨厌的)eval(),但您可以使用一种偷偷摸摸的方式来做到这一点。

var sum = eval(elmt.join('+')), avg = sum / elmt.length;
document.write("The sum of all the elements is: " + sum + " The average of all the elements is: " + avg + "<br/>");

Here is a quick addition to the “Math” object in javascript to add a “average” command to it!!这是在 javascript 中快速添加“数学”对象以添加“平均”命令!

Math.average = function(input) {
  this.output = 0;
  for (this.i = 0; this.i < input.length; this.i++) {
    this.output+=Number(input[this.i]);
  }
  return this.output/input.length;
}

Then i have this addition to the “Math” object for getting the sum!然后我将这个添加到“数学”对象中以​​获得总和!

Math.sum = function(input) {
  this.output = 0;
  for (this.i = 0; this.i < input.length; this.i++) {
    this.output+=Number(input[this.i]);
  }
  return this.output;
}

So then all you do is那么你要做的就是

alert(Math.sum([5,5,5])); //alerts “15”
alert(Math.average([10,0,5])); //alerts “5”

And where i put the placeholder array just pass in your variable (The input if they are numbers can be a string because of it parsing to a number!)我把占位符数组放在哪里只是传入你的变量(如果它们是数字,输入可以是一个字符串,因为它解析为一个数字!)

set your for loop counter to 0.... you're getting element 9 and then you're done as you have it now.将你的 for 循环计数器设置为 0 .... 你得到元素 9,然后你就完成了,就像现在一样。 The other answers are basic math.其他答案是基本数学。 Use a variable to store your sum (need to cast the strings to ints), and divide by your array length.使用变量来存储总和(需要将字符串转换为整数),然后除以数组长度。

"

Start by defining all of the variables we plan on using.首先定义我们计划使用的所有变量。 You'll note that for the numbers<\/code> array, I'm using the literal notation of []<\/code> as opposed to the constructor method array()<\/code> .您会注意到,对于numbers<\/code>数组,我使用[]<\/code>的文字表示法,而不是构造函数方法array()<\/code> 。 Additionally, I'm using a shorter method to set multiple variables to 0.此外,我使用更短的方法将多个变量设置为 0。

var numbers = [], count = sum = avg = 0;

I am just building on Abdennour TOUMI's answer.我只是建立在 Abdennour TOUMI 的回答之上。 here are the reasons why:以下是原因:

1.) I agree with Brad, I do not think it is a good idea to extend object that we did not create. 1.) 我同意布拉德的观点,我认为扩展我们没有创建的对象不是一个好主意。

2.) array.length<\/code> is exactly reliable in javascript, I prefer Array.reduce<\/code> beacuse a=[1,3];a[1000]=5;<\/code> 2.) array.length<\/code>在javascript中完全可靠,我更喜欢Array.reduce<\/code>因为a=[1,3];a[1000]=5;<\/code> , now a.length<\/code> would return 1001<\/code> . ,现在a.length<\/code>将返回1001<\/code> 。

function getAverage(arry){
    // check if array
    if(!(Object.prototype.toString.call(arry) === '[object Array]')){
        return 0;
    }
    var sum = 0, count = 0; 
    sum = arry.reduce(function(previousValue, currentValue, index, array) {
        if(isFinite(currentValue)){
            count++;
            return previousValue+ parseFloat(currentValue);
        }
        return previousValue;
    }, sum);
    return count ? sum / count : 0; 
};
Array.prototype.avg=function(fn){
    fn =fn || function(e,i){return e};
    return (this.map(fn).reduce(function(a,b){return parseFloat(a)+parseFloat(b)},0) / this.length ) ; 
};

On evergreen browsers you can use arrow functions avg = [1,2,3].reduce((a,b) => (a+b);<\/code>在常青浏览器上,您可以使用箭头函数avg = [1,2,3].reduce((a,b) => (a+b);<\/code>

Running it 100,000 times, the time difference between the for loop approach and reduce is negligible.运行它 100,000 次,for 循环方法和 reduce 之间的时间差可以忽略不计。

 s=Date.now();for(i=0;i<100000;i++){ n=[1,2,3]; a=n.reduce((a,b) => (a+b)) \/ n.length }; console.log("100k reduce took " + (Date.now()-s) + "ms."); s=Date.now();for(i=0;i<100000;i++){n=[1,2,3]; nl=n.length; a=0; for(j=nl-1;j>0;j--){a=a+n[j];} a\/nl }; console.log("100k for loop took " + (Date.now()-s) + "ms."); s=Date.now();for(i=0;i<1000000;i++){n=[1,2,3]; nl=n.length; a=0; for(j=nl-1;j>0;j--){a=a+n[j];} a\/nl }; console.log("1M for loop took " + (Date.now()-s) + "ms."); s=Date.now();for(i=0;i<1000000;i++){ n=[1,2,3]; a=n.reduce((a,b) => (a+b)) \/ n.length }; console.log("1M reduce took " + (Date.now()-s) + "ms."); \/* * RESULT on Chrome 51 * 100k reduce took 26ms. * 100k for loop took 35ms. * 10M for loop took 126ms. * 10M reduce took 209ms. *\/<\/code><\/pre>

"

If you are in need of the average and can skip the requirement of calculating the sum, you can compute the average with a single call of reduce:如果您需要平均值并且可以跳过计算总和的要求,您可以通过一次调用 reduce 来计算平均值:

// Assumes an array with only values that can be parsed to a Float
var reducer = function(cumulativeAverage, currentValue, currentIndex) {
  // 1. multiply average by currentIndex to find cumulative sum of previous elements
  // 2. add currentValue to get cumulative sum, including current element
  // 3. divide by total number of elements, including current element (zero-based index + 1)
  return (cumulativeAverage * currentIndex + parseFloat(currentValue))/(currentIndex + 1)
}
console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].reduce(reducer, 0)); // => 5.5
console.log([].reduce(reducer, 0)); // => 0
console.log([0].reduce(reducer, 0)); // => 0
console.log([].reduce(reducer, 0)); // => 0
console.log([,,,].reduce(reducer, 0)); // => 0
console.log([].reduce(reducer, 0)); // => 0

If anyone ever needs it - Here is a recursive average.如果有人需要它 - 这是一个递归平均值。

In the context of the original question, you may want to use the recursive average if you allowed the user to insert additional values and, without incurring the cost of visiting each element again, wanted to "update" the existing average.在原始问题的上下文中,如果您允许用户插入附加值并且不产生再次访问每个元素的成本,您可能希望使用递归平均值,并且想要“更新”现有平均值。

/**
 * Computes the recursive average of an indefinite set
 * @param {Iterable<number>} set iterable sequence to average
 * @param {number} initAvg initial average value
 * @param {number} initCount initial average count
 */
function average(set, initAvg, initCount) {
  if (!set || !set[Symbol.iterator])
    throw Error("must pass an iterable sequence");

  let avg = initAvg || 0;
  let avgCnt = initCount || 0;
  for (let x of set) {
    avgCnt += 1;
    avg = avg * ((avgCnt - 1) / avgCnt) + x / avgCnt;
  }
  return avg; // or {avg: avg, count: avgCnt};
}

average([2, 4, 6]);    //returns 4
average([4, 6], 2, 1); //returns 4
average([6], 3, 2);    //returns 4
average({
  *[Symbol.iterator]() {
    yield 2; yield 4; yield 6;
  }
});                    //returns 4

Having read the other choices, I will try to make a simpler version for the future viewers, elaborating on the existing code and not creating a more elegant one.在阅读了其他选择之后,我将尝试为未来的观众制作一个更简单的版本,详细说明现有的代码,而不是创建一个更优雅的代码。 First of all, you declared the numbers as strings.首先,您将数字声明为字符串。 Apart from the .parseInt we can also do:除了 .parseInt 我们还可以这样做:

const numberConverter = elmt.map(Number);

So what map does is that it "returns a copy of the original array".所以 map 所做的是它“返回原始数组的副本”。 But I convert its values to numbers.但我将其值转换为数字。 Then we can use the reduce method (It can also be simpler, but I am writing easy to read versions and I also have 2 average methods) What the reduce method does is it has an accumulator that gets bigger and bigger if you add values to it, as it iterates through the array and adds (in this case) the currentValue to it.:然后我们可以使用 reduce 方法(它也可以更简单,但我正在编写易于阅读的版本,并且我还有 2 个平均方法)reduce 方法的作用是它有一个累加器,如果你将值添加到它,因为它遍历数组并将(在本例中) currentValue 添加到它。:

var i;
const elmt = new Array();
elmt[0] = '0';
elmt[1] = '1';
elmt[2] = '2';
elmt[3] = '3';
elmt[4] = '4';
elmt[5] = '7';
elmt[6] = '8';
elmt[7] = '9';
elmt[8] = '10';
elmt[9] = '11';

console.log(elmt);

const numberConverter = elmt.map(Number);

const sum = numberConverter.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);

const average = numberConverter.reduce(
  (accumulator, currentvalue, index, numArray) => {
    return accumulator + currentvalue / numArray.length;
  },
  0
);

const average2 =
  numberConverter.reduce(
    (accumulator, currentValue) => accumulator + currentValue,
    0
  ) / numberConverter.length;

for (i = 9; i < 10; i++) {
  console.log(
    `The sum of all the elements is: ${sum}. <br> The average of all the elements is: ${average2}`
  );}

Just for kicks:只是为了踢球:

var elmt = [0, 1, 2,3, 4, 7, 8, 9, 10, 11], l = elmt.length, i = -1, sum = 0;
for (; ++i < l; sum += elmt[i])
    ;
document.body.appendChild(document.createTextNode('The sum of all the elements is: ' + sum + ' The average of all the elements is: ' + (sum / l)));

I think we can do like我认为我们可以这样做

var k=elmt.reduce(function(a,b){return parseFloat(a+parseFloat(b));})
var avg=k/elmt.length; 
console.log(avg);

I am using parseFloat twice because when 1) you add (a)9+b("1") number then result will be "91" but we want addition.我使用 parseFloat 两次,因为当 1) 添加 (a)9+b("1") 数字时,结果将是“91”,但我们想要添加。 so i used parseFloat所以我使用了 parseFloat

2)When addition of (a)9+parseFloat("1") happen though result will be "10" but it will be in string which we don't want so again i used parseFloat. 2)当添加(a)9 + parseFloat(“1”)时,虽然结果将是“10”,但它会在我们不想要的字符串中,所以我再次使用了parseFloat。

I hope i am clear.我希望我很清楚。 Suggestions are welcome欢迎提出建议

Here is my rookie way of simply finding the avg.这是我简单地找到平均值的新手方法。 Hope this helps somebody.希望这可以帮助某人。

function numAvg(num){
    var total = 0;
    for(var i = 0;i < num.length; i++) { 
        total+=num[i];
    }
    return total/num.length;
}

这是你的一个班轮:

var average = arr.reduce((sum,item,index,arr)=>index !== arr.length-1?sum+item:sum+item/arr.length,0)

I think this may be a direct solution to calculate the average with a for loop and function.我认为这可能是使用 for 循环和函数计算平均值的直接解决方案。

var elmts = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

function average(arr) {
    var total = 0;
    for (var i = 0; i < arr.length; i++) {
        total += arr[i];
    }
        console.log(Math.round(total/arr.length));
}

average(elmts);

There seem to be an endless number of solutions for this but I found this to be concise and elegant.似乎有无数种解决方案,但我发现这简洁而优雅。

const numbers = [1,2,3,4];
const count = numbers.length;
const reducer = (adder, value) => (adder + value);
const average = numbers.map(x => x/count).reduce(reducer);
console.log(average); // 2.5

Unless I missed something, every solution up to this point uses the length of the list to calculate the average after summing the values.除非我错过了什么,否则到目前为止的每个解决方案都使用列表的长度来计算对值求和后的平均值。

There is a downside to this approach that a slightly modified, yet still simple algorithm will address without the downsides.这种方法有一个缺点,一个稍微修改但仍然简单的算法将解决没有缺点的问题。

The downside is that you assuming that there won't be an overflow by summing all the numbers.缺点是您假设通过对所有数字求和不会溢出。 If you have a lot of numbers that are very big, and you add them all up, they may exceed the maximum size that can fit into the data type.如果您有很多非常大的数字,并且将它们全部加起来,它们可能会超过可以容纳数据类型的最大大小。

A better approach is to simply calculate the average as you go, rather than summing it and then dividing with the length at the end:更好的方法是简单地计算平均值,就像你 go 一样,而不是求和然后除以最后的长度:

function getAvg(values) {
    return values.reduce((m, x, i) => m + (x - m) / (i + 1), 0)
}

Props to Knuth's "Art of Computer Programming" vol. Knuth 的“计算机编程艺术”卷的道具。 2. 2.

just for fun纯娱乐

 let avg = [81, 77, -88, 195, 6.8].reduce((a,e,i) => (a*i+e)/(i+1)); console.log(avg)

Average of HTML content itens HTML 内容的平均数

With jQuery or Javascript's querySelector you have direct acess to formated data... Example:使用 jQuery 或 Javascript 的querySelector ,您可以直接访问格式化数据... 示例:

<p>Elements for an average: <span class="m">2</span>, <span class="m">4</span>,
   <span class="m">2</span>, <span class="m">3</span>.
</p>

So, with jQuery you have所以,使用 jQuery 你有

var A = $('.m')
  .map(function(idx) { return  parseInt($(this).html()) })
  .get();
var AVG = A.reduce(function(a,b){return a+b}) / A5.length;

See other more 4 ways (!) to access itens and average it: http://jsfiddle.net/4fLWB/查看其他 4 种方式(!)来访问 itens 并对其进行平均:http: //jsfiddle.net/4fLWB/

var arr = [1,2,3,4,5] var arr = [1,2,3,4,5]

function avg(arr){
  var sum = 0;
  for (var i = 0; i < arr.length; i++) {
    sum += parseFloat(arr[i])
  }
  return sum / i;
}

avg(arr) ======>>>> 3平均(arr)======>>>> 3

This works with strings as numbers or numbers in the array.这适用于字符串作为数组中的数字或数字。

    var scores =[90, 98, 89, 100, 100, 86, 94];
        var sum = 0;
        var avg = 0;
        for(var i = 0; i < scores.length;i++){
  //Taking sum of all the arraylist
            sum = sum + scores[i];   
                }
  //Taking average     
             avg = sum/scores.length;        
  //this is the function to round a decimal no    
             var round = avg.toFixed();
             console.log(round);

I would recommend D3 in this case. 在这种情况下我会推荐D3。 It is the most readable (and provides 2 different kinds of averages) 它是最具可读性的(并提供2种不同的平均值)

let d3 = require('d3');
let array = [1,2,3,4];
let sum = d3.sum(array); //10
let mean = d3.mean(array); //2.5
let median = d3.median(array); 

I had exactly 10 elements (like in the example) so I did: 我有10个元素(如示例中所示),所以我做了:

( elmt[0] + elmt[1] + elmt[2] + elmt[3] + elmt[4] +
  elmt[5] + elmt[6] + elmt[7] + elmt[8] + elmt[9] ) / 10

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

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