Given an array [1, 2, 3, 4]
, how can I find the sum of its elements? (In this case, the sum would be 10
.)
I thought $.each might be useful,
Why not reduce? It's usually a bit counter intuitive, but using it to find a sum is pretty straightforward:
var a = [1,2,3];
var sum = a.reduce(function(a, b) { return a + b; }, 0);
OK, imagine you have this array below:
const arr = [1, 2, 3, 4];
Let's start looking into many different ways to do it as I couldn't find any comprehensive answer here:
1) Using built-in reduce()
function total(arr) {
if(!Array.isArray(arr)) return;
return arr.reduce((a, v)=>a + v);
}
2) Using for loop
function total(arr) {
if(!Array.isArray(arr)) return;
let totalNumber = 0;
for (let i=0,l=arr.length; i<l; i++) {
totalNumber+=arr[i];
}
return totalNumber;
}
3) Using while loop
function total(arr) {
if(!Array.isArray(arr)) return;
let totalNumber = 0, i=-1;
while (++i < arr.length) {
totalNumber+=arr[i];
}
return totalNumber;
}
4) Using array forEach
function total(arr) {
if(!Array.isArray(arr)) return;
let sum=0;
arr.forEach(each => {
sum+=each;
});
return sum;
};
and call it like this:
total(arr); //return 10
It's not recommended to prototype something like this to Array...
A standard JavaScript solution:
var addition = [];
addition.push(2);
addition.push(3);
var total = 0;
for (var i = 0; i < addition.length; i++)
{
total += addition[i];
}
alert(total); // Just to output an example
/* console.log(total); // Just to output an example with Firebug */
This works for me (the result should be 5). I hope there is no hidden disadvantage in this kind of solution.
A few people have suggested adding a .sum()
method to the Array.prototype
. This is generally considered bad practice so I'm not suggesting that you do it.
If you still insist on doing it then this is a succinct way of writing it:
Array.prototype.sum = function() {return [].reduce.call(this, (a,i) => a+i, 0);}
then: [1,2].sum(); // 3
Note that the function added to the prototype is using a mixture of ES5 and ES6 function and arrow syntax. The function
is declared to allow the method to get the this
context from the Array
that you're operating on. I used the =>
for brevity inside the reduce
call.
var total = 0;
$.each(arr,function() {
total += this;
});
Use reduce
let arr = [1, 2, 3, 4];
let sum = arr.reduce((v, i) => (v + i));
console.log(sum);