This'd be exactly the job for reduce.
If you're using ECMAScript 2015 (aka ECMAScript 6):
const sum = [1, 2, 3].reduce((partialSum, a) => partialSum + a, 0); console.log(sum); // 6
For older JS:
const sum = [1, 2, 3].reduce(add, 0); // with initial value to avoid when the array is empty function add(accumulator, a) { return accumulator + a; } console.log(sum); // 6
Isn't that pretty? :-)
Ry-♦
211k54 gold badges441 silver badges455 bronze badges
answered May 25, 2013 at 16:30
Florian MargaineFlorian Margaine
55.8k14 gold badges90 silver badges116 bronze badges
5
Recommended (reduce with default value)
Array.prototype.reduce can be used to iterate through the array, adding the current element value to the sum of the previous element values.
console.log( [1, 2, 3, 4].reduce((a, b) => a + b, 0) ) console.log( [].reduce((a, b) => a + b, 0) )
Without default value
You get a TypeError
console.log( [].reduce((a, b) => a + b) )
Prior to ES6's arrow functions
console.log( [1,2,3].reduce(function(acc, val) { return acc + val; }, 0) ) console.log( [].reduce(function(acc, val) { return acc + val; }, 0) )
Non-number inputs
If non-numbers are possible inputs, you may want to handle that?
console.log( ["hi", 1, 2, "frog"].reduce((a, b) => a + b) ) let numOr0 = n => isNaN(n) ? 0 : n console.log( ["hi", 1, 2, "frog"].reduce((a, b) => numOr0(a) + numOr0(b)) )
Non-recommended dangerous eval use
We can use eval to execute a string representation of JavaScript code. Using the Array.prototype.join function to convert the array to a string, we change [1,2,3] into "1+2+3", which evaluates to 6.
console.log( eval([1,2,3].join('+')) ) //This way is dangerous if the array is built // from user input as it may be exploited eg: eval([1,"2;alert('Malicious code!')"].join('+'))
Of course displaying an alert isn't the worst thing that could happen. The only reason I have included this is as an answer Ortund's question as I do not think it was clarified.
answered Apr 12, 2017 at 7:31
OwChallieOwChallie
13.6k1 gold badge9 silver badges11 bronze badges
2
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);
answered Jan 16, 2012 at 9:45
Casey RodarmorCasey Rodarmor
14.2k5 gold badges29 silver badges32 bronze badges
10
var arr = [1, 2, 3, 4]; var total = 0; for (var i in arr) { total += arr[i]; }
Kartikey
3,9644 gold badges13 silver badges36 bronze badges
answered Aug 4, 2009 at 22:31
AmberAmber
487k81 gold badges616 silver badges545 bronze badges
10
var total = 0; $.each(arr,function() { total += this; });
answered Aug 4, 2009 at 22:30
Tyler CarterTyler Carter
59.7k20 gold badges126 silver badges148 bronze badges
8
Anyone looking for a functional oneliner like me?
Assuming:
const arr = [1, 2, 3, 4];Here's the oneliner for modern JS:
sum = arr.reduce((a, b) => a + b, 0);(If you happen to have to support ye olde IE without arrow functions:)
sum = arr.reduce(function (a, b) {return a + b;}, 0);Note that 0 is the initial value here, so you can use that as offset if needed. Also note that this initial value is needed, otherwise calling the function with an empty array will error.
answered Feb 2, 2015 at 17:54
geek-merlingeek-merlin
1,43216 silver badges12 bronze badges
0
If you happen to be using Lodash you can use the sum function
array = [1, 2, 3, 4]; sum = _.sum(array); // sum == 10
simhumileco
28.3k16 gold badges126 silver badges106 bronze badges
answered Jan 7, 2016 at 14:26
4
This is possible by looping over all items, and adding them on each iteration to a sum-variable.
var array = [1, 2, 3]; for (var i = 0, sum = 0; i < array.length; sum += array[i++]);JavaScript doesn't know block scoping, so sum will be accesible:
console.log(sum); // => 6The same as above, however annotated and prepared as a simple function:
function sumArray(array) { for ( var index = 0, // The iterator length = array.length, // Cache the array length sum = 0; // The total amount index < length; // The "for"-loop condition sum += array[index++] // Add number on each iteration ); return sum; }answered May 25, 2013 at 16:03
yckartyckart
30.8k9 gold badges117 silver badges127 bronze badges
3
arr.reduce(function (a, b) { return a + b; });
Reference: Array.prototype.reduce()
answered Dec 13, 2014 at 7:49
onhoutonhout
2873 silver badges3 bronze badges
2
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 10It's not recommended to prototype something like this to Array...
answered Dec 31, 2017 at 17:38
AlirezaAlireza
95.5k26 gold badges263 silver badges166 bronze badges
Funny approach:
eval([1,2,3].join("+"))answered Oct 20, 2016 at 15:17
electronelectron
7637 silver badges17 bronze badges
5
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.
answered Sep 1, 2012 at 14:23
nanonano
1271 silver badge2 bronze badges
3
I am a beginner with JavaScript and coding in general, but I found that a simple and easy way to sum the numbers in an array is like this:
var myNumbers = [1,2,3,4,5] var total = 0; for(var i = 0; i < myNumbers.length; i++){ total += myNumbers[i]; }Basically, I wanted to contribute this because I didn't see many solutions that don't use built-in functions, and this method is easy to write and understand.
answered Apr 19, 2016 at 16:46
1
You can try the following code:
[1, 2, 3, 4].reduce((pre,curr)=>pre+curr,0)answered Apr 7 at 0:21
Use a for loop:
const array = [1, 2, 3, 4]; let result = 0; for (let i = 0; i < array.length - 1; i++) { result += array[i]; } console.log(result); // Should give 10Or even a forEach loop:
const array = [1, 2, 3, 4]; let result = 0; array.forEach(number => { result += number; }) console.log(result); // Should give 10For simplicity, use reduce:
const array = [10, 20, 30, 40]; const add = (a, b) => a + b const result = array.reduce(add); console.log(result); // Should give 100
Hunter
2,71820 silver badges22 bronze badges
answered Aug 22, 2019 at 10:04
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.
answered Oct 3, 2017 at 19:57
GuyGuy
63.8k94 gold badges250 silver badges318 bronze badges
1
ES6 for..of
let total = 0; for (let value of [1, 2, 3, 4]) { total += value; }answered Dec 2, 2020 at 4:39
caiohamamuracaiohamamura
2,06519 silver badges22 bronze badges
A short piece of JavaScript code would do this job:
var numbers = [1,2,3,4]; var totalAmount = 0; for (var x = 0; x < numbers.length; x++) { totalAmount += numbers[x]; } console.log(totalAmount); //10 (1+2+3+4)
answered Dec 6, 2014 at 20:23
var totally = eval(arr.join('+'))
That way you can put all kinds of exotic things in the array.
var arr = ['(1/3)','Date.now()','foo','bar()',1,2,3,4]I'm only half joking.
answered Sep 7, 2016 at 11:06
user40521user40521
1,85919 silver badges7 bronze badges
2
Use reduce
let arr = [1, 2, 3, 4]; let sum = arr.reduce((v, i) => (v + i)); console.log(sum);
Paul Roub
36k27 gold badges80 silver badges88 bronze badges
answered Jun 23, 2017 at 18:40
DamienDamien
1,4951 gold badge13 silver badges24 bronze badges
No need to initial value! Because if no initial value is passed, the callback function is not invoked on the first element of the list, and the first element is instead passed as the initial value. Very cOOl feature :)
[1, 2, 3, 4].reduce((a, x) => a + x) // 10 [1, 2, 3, 4].reduce((a, x) => a * x) // 24 [1, 2, 3, 4].reduce((a, x) => Math.max(a, x)) // 4 [1, 2, 3, 4].reduce((a, x) => Math.min(a, x)) // 1answered Dec 11, 2017 at 15:34
YasYas
4,3071 gold badge35 silver badges22 bronze badges
Here's an elegant one-liner solution that uses stack algorithm, though one may take some time to understand the beauty of this implementation.
const getSum = arr => (arr.length === 1) ? arr[0] : arr.pop() + getSum(arr); getSum([1, 2, 3, 4, 5]) //15Basically, the function accepts an array and checks whether the array contains exactly one item. If false, it pop the last item out of the stack and return the updated array.
The beauty of this snippet is that the function includes arr[0] checking to prevent infinite looping. Once it reaches the last item, it returns the entire sum.
answered Jan 5, 2018 at 7:48
Rex LowRex Low
1,8962 gold badges18 silver badges45 bronze badges
2
Accuracy
Sort array and start sum form smallest numbers (snippet shows difference with nonsort)
[...arr].sort((a,b)=>a-b).reduce((a,c)=>a+c,0)For multidimensional array of numbers use arr.flat(Infinity)
answered Sep 19, 2019 at 7:43
Kamil KiełczewskiKamil Kiełczewski
75.4k26 gold badges335 silver badges311 bronze badges
Those are really great answers, but just in case if the numbers are in sequence like in the question ( 1,2,3,4) you can easily do that by applying the formula (n*(n+1))/2 where n is the last number
answered Feb 19, 2017 at 10:05
SantoshSantosh
93712 silver badges11 bronze badges
1
You can combine reduce() method with lambda expression:
[1, 2, 3, 4].reduce((accumulator, currentValue) => accumulator + currentValue);answered May 14, 2018 at 5:05
antonjsantonjs
13.7k11 gold badges62 silver badges91 bronze badges
With reduce()
[1, 2, 3, 4].reduce((a, b) => a + b, 0); // 10With forEach()
let sum = 0; [1, 2, 3, 4].forEach(n => sum += n); sum; // 10With Parameter
function arrSum(arr) { sum = 0; arr.forEach(n => sum += n); return sum; } arrSum([1, 2, 3, 4]) // 10answered Oct 16, 2021 at 16:55
i saw all answers going for 'reduce' solution
answered Feb 28, 2018 at 14:59
Adrian SwifterAdrian Swifter
791 gold badge1 silver badge9 bronze badges
very simple
step 1 we should have an array like :
const arrayNumber = [500,152,154,1555,12445];step 2 (you can ignore this step if) step is to be sur that all values in table are number for that
let newArray = []; for (let i = 0; i < arrayNumber.length; i++) { newArray.push(parseInt(arrayNumber[i], 10)); }step 3
const sumInArray = dataData.reduce( (a, b) => a + b);finally
console.log(sumInArray);answered Apr 8, 2021 at 21:56
Simplest answer to understand underlying process:
let array = [10, 20, 30, 40, 50] let total = 0 for(let i in array) { total += array[i] } console.log(total)& if you're already familiar with underlying process then built-in method can save you time:
let array = [10, 20, 30, 40, 50] let total = array.reduce((x, y) => x + y) console.log(total)answered Jul 15, 2021 at 13:21