1294

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, but I'm not sure how to implement it.

royhowie
  • 10,805
  • 14
  • 48
  • 67
akano1
  • 38,208
  • 18
  • 49
  • 65
  • 30
    @tereško Unwillingness to google is not a valid close reason on Stackoverflow. Please downvote if you feel that the question is not well (re)searched. (Also judging by the answers - this seems to be a highly controversial topic with many possible solutions including some highly upvoted bad practises (eval) - surprisingly.) – Trilarion Jan 07 '16 at 10:26
  • 12
    Note: most answers here essentially compute `a[0] + a[1] + ...`, which can turn into string concatenation if the array has non-number elements. E.g. `['foo', 42].reduce((a,b)=>a+b, 0) === "0foo42"`. – Beni Cherniavsky-Paskin Jan 10 '16 at 17:00
  • 3
    No built in reducer one could feed to Array.reduce? Thinking something like `[1,2,3].reduce(Math.sum)`. – Phil Mar 24 '20 at 10:15

56 Answers56

1393

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

DEMO

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

mikemaccana
  • 94,893
  • 84
  • 350
  • 433
Florian Margaine
  • 54,552
  • 14
  • 89
  • 116
1235

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.

Stan Kurdziel
  • 5,108
  • 1
  • 38
  • 40
OwChallie
  • 13,087
  • 1
  • 9
  • 11
  • 19
    You do know that this magic with `reduce()` is still 25-30% slower than a simple indexed `for()` loop after long years? https://jsperf.com/reduce-vs-loop/4 – tevemadar Oct 29 '19 at 10:54
242

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);
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Casey Rodarmor
  • 13,916
  • 5
  • 29
  • 32
  • 4
    IE8 doesn't support it, and it doesn't look like jQuery intends on adding it. However, Prototype has it. – Ishmael Smyrnow Apr 10 '12 at 20:33
  • 5
    @Ishmael, you can use UnderscoreJS, which falls back to the browser's implementation if available, or implements its own otherwise. – Pablo Diaz Mar 13 '13 at 23:09
  • 1
    Very nice. Looking at the [execution time test](http://stackoverflow.com/a/12995054/1536976) of Riking, `reduce` also seems to be very efficient. – Trilarion Jan 07 '16 at 12:53
  • 5
    What's counter-intuitive about `reduce()`? – canon Jan 07 '16 at 14:48
  • @canon: To get the sum, you would normally add all the numbers, instead of reducing them? – s4nji Jan 26 '16 at 16:46
  • 3
    @s4nji `Array.prototype.reduce()` _reduces_ an array to a single return value. – canon Jan 26 '16 at 16:56
  • 1
    @canon The meaning of (the word) reduce itself (without knowing what `Array.prototype.reduce()` does) is the opposite of (the word) adding, which is normally done to calculate a sum, therefore it is counter-intuitive. – s4nji Jan 26 '16 at 17:21
  • 6
    @s4nji ...unless you are reducing a sauce - in which case you are boling it down to its essentials, i.e. the sum of all flavors without the water overhead. :-) – CB Du Rietz Apr 24 '16 at 12:05
  • 2
    I can see how reduce is not intuitive in the given usage. You could not reasonably consider that reduce would work as an addition tool in the given case without the prior knowledge of how the function works. – CodingInTheUK May 13 '16 at 10:39
  • 1
    @canon [what-is-the-problem-with-reduce](http://stackoverflow.com/questions/181543/what-is-the-problem-with-reduce) – None Jun 28 '16 at 18:46
117
var arr = [1, 2, 3, 4];
var total = 0;
for (var i in arr) {
  total += arr[i];
}
Kartikey
  • 3,658
  • 4
  • 13
  • 35
Amber
  • 477,764
  • 81
  • 611
  • 541
  • 3
    This is way faster than the jQuery.each() solution above. – Angry Dan Aug 24 '11 at 09:39
  • 49
    @Sprog: However, using `(var i=0; i – Riking Oct 21 '12 at 04:36
  • @Riking: Yay for micro-optimization! – Angry Dan Oct 22 '12 at 10:09
  • 16
    Using `for... in` loops on arrays works in this case _ coincidentally_ and because arrays extend objects. Riking's solution is better – Benjamin Gruenbaum May 07 '13 at 03:29
  • for..in loops are the most expensive loops, so its important to keep that in mind and use them ONLY when needed, in this case you can easily set local variables for the index and array length. then use while or for to loop through the array outputting the value like arr[index] – Josh Bedo Feb 24 '14 at 14:31
  • 2
    @BenjaminGruenbaum provided that nothing has added enumerable properties to array's prototype... – canon Jan 07 '16 at 14:47
  • I'm no javascript guru but ... doesn't `i` takes the array's values, not indexes? – YSC Jan 07 '16 at 16:45
  • 1
    @YSC no, it does not. A `for...in` loop in JavaScript takes the indices, which is a common stumbling block for coders that expect to get the values. (Try `for(var i in [1,2,3]) { console.log(i); }` in a console.) – Amber Jan 10 '16 at 02:52
  • 1
    http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea – Evan Trimboli May 24 '16 at 21:17
  • @YSC A `for...in` loop accesses the indices in arrays or keys in objects. If you want to access the values directly, you can use a `for...of` loop with arrays or other iterable objects like strings but it doesn't work with objects. For objects, you'll need to use `for...in` to access the keys and then get the values from there. – AlwaysLearning Oct 30 '21 at 21:01
62
var total = 0;
$.each(arr,function() {
    total += this;
});
Tyler Carter
  • 59,289
  • 20
  • 126
  • 148
  • 101
    Please, please, please use the answer with `reduce` below; do not declare mutable vars when you do not have too. – Bruno Grieder Feb 27 '15 at 14:29
  • 10
    This answer is under [meta discussion](http://meta.stackoverflow.com/q/314157/871050) – Madara's Ghost Jan 07 '16 at 10:24
  • 12
    Please do not use this, even though it is the "accepted answer"; the answer by Florian below is much better! – Andy Sinclair Jan 07 '16 at 14:13
  • 4
    jQuery's `$.each()` and friends were a win (if you're OK with the dependency of course) before JS arrays gained builtin `.reduce()`, `.forEach()` etc. Nowdays the builtin `reduce` is clearly the one *idiomatic* way to write it; if you still want to support IE8 which lacks `.reduce` (and don't want a polyfill), I'd say fall back to a `for` loop. – Beni Cherniavsky-Paskin Jan 10 '16 at 12:00
  • 17
    @BrunoGrieder "Do not declare mutable vars when you do not have to" is an extremely biased opinion about an *imperative language*, it is hardly a code smell by any stretch of the imagination. There's absolutely nothing wrong with Tyler's answer, and the only difference between Tyler's and Florian's is style. – Rob Jan 11 '16 at 09:43
  • 6
    From OP: _I thought $.each might be useful, but I'm not sure how to implement it._ This maybe not be the best, but answer the OP's request. –  Jan 11 '16 at 15:30
  • 6
    The criticisms to this answer are ridiculous. The question specifically tags jquery and asks about $.each. Is reduce the right answer for most people asking this question? Of course it is, but that's why we have multiple answers and brains to evaluate them against our specific use case. – aw04 Oct 17 '16 at 14:37
  • 1
    I think the amount of controversy this caused 7 years after it was written is hilarious. – Tyler Carter Sep 30 '19 at 10:47
50

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.

geek-merlin
  • 1,312
  • 15
  • 12
50

If you happen to be using Lodash you can use the sum function

array = [1, 2, 3, 4];
sum = _.sum(array); // sum == 10
simhumileco
  • 27,137
  • 16
  • 123
  • 105
David says Reinstate Monica
  • 18,041
  • 20
  • 73
  • 118
35

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); // => 6

The 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;
}
yckart
  • 30,290
  • 9
  • 117
  • 125
  • 13
    While clever, I'd find code declaring `sum` outside the loop much more readable. – Beni Cherniavsky-Paskin Jan 05 '16 at 13:57
  • 1
    @BeniCherniavsky-Paskin Yeah, same here... Don't know why I did it this way that day... However, I'll let it as it is! It's just an example of *how we might could...* ;) – yckart Jan 05 '16 at 14:19
  • Since ES6, javascript DOES know block scoping with `const` and `let`. So you can declare `sum` outside the `for` loop as `let sum = 0;`. You can also cache the array length before the loop as `const length = array.length;` – KSK Nov 22 '17 at 01:35
28
arr.reduce(function (a, b) {
    return a + b;
});

Reference: Array.prototype.reduce()

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
onhout
  • 289
  • 3
  • 3
17

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

Alireza
  • 93,149
  • 25
  • 259
  • 162
13

Funny approach:

eval([1,2,3].join("+"))
electron
  • 767
  • 7
  • 17
  • 6
    Please could you expand on this answer by explaining what is happening in this code? Why does it work? What does it do exactly? These things help to improve the quality of the answer. – Ortund Oct 21 '16 at 08:54
  • @user40521 has already answered this the way i think. I didn't see it. – electron Oct 21 '16 at 09:34
  • While this is short and sweet, and certainly interesting, it is also very inefficient. Using `reduce` is definitely preferable for the majority, if not all, cases. – Ninjakannon Jan 15 '18 at 10:45
  • Errm, `[1,"2;YourProgram.ripToShreds();3",4]` – Radvylf Programs Oct 25 '18 at 12:22
  • So I'm getting `NaN` when trying `eval(['alert("removing your computer")',2,3].join("+"))` wrong answer 0/10 – Adam Pietrasiak Mar 27 '19 at 08:54
12

You can also use reduceRight.

[1,2,3,4,5,6].reduceRight(function(a,b){return a+b;})

which results output as 21.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight

Rohit Bhalke
  • 137
  • 1
  • 5
  • Should be faster in chrome because the optimization to javascript looping (i.e. decrementing the length) can also be applied to the underlying assembly to make it run faster. – Jack G Mar 13 '17 at 19:01
11

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.

nano
  • 127
  • 1
  • 2
9

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.

Community
  • 1
  • 1
  • 1
    How is this any different from [this 2012 answer](http://stackoverflow.com/a/12228538/1269037) or [this 2014 answer](http://stackoverflow.com/a/27336090/1269037)? There's two solutions you haven't seen. – Dan Dascalescu Feb 09 '17 at 06:58
7

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 10

Or even a forEach loop:

const array = [1, 2, 3, 4];
let result = 0;

array.forEach(number => {
  result += number;
})

console.log(result); // Should give 10

For 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,538
  • 18
  • 21
6
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.

user40521
  • 1,798
  • 18
  • 6
6

ES6 for..of

let total = 0;

for (let value of [1, 2, 3, 4]) {
    total += value; 
}
caiohamamura
  • 2,005
  • 18
  • 21
5

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)
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
5

Use reduce

let arr = [1, 2, 3, 4];

let sum = arr.reduce((v, i) => (v + i));

console.log(sum);
Paul Roub
  • 35,848
  • 27
  • 79
  • 88
Damien Asseya
  • 1,547
  • 1
  • 13
  • 23
5

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.

Guy
  • 62,854
  • 93
  • 248
  • 316
  • If you're going to mess with prototypes (and you shouldn't), a `Math.prototype.sum` method would be more appropriate. – Joe Maffei May 23 '22 at 20:38
5

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)) // 1
Yas
  • 4,117
  • 1
  • 34
  • 22
5

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]) //15

Basically, 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.

Rex Low
  • 1,836
  • 2
  • 18
  • 44
5

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)

arr=[.6,9,.1,.1,.1,.1]

sum     =                       arr.reduce((a,c)=>a+c,0)
sortSum = [...arr].sort((a,b)=>a-b).reduce((a,c)=>a+c,0)

console.log('sum:     ',sum);
console.log('sortSum:',sortSum);
console.log('sum==sortSum :', sum==sortSum);

// we use .sort((a,b)=>a-b) instead .sort() because
// that second one treat elements like strings (so in wrong way)
// e.g [1,10,9,20,93].sort() -->  [1, 10, 20, 9, 93]

For multidimensional array of numbers use arr.flat(Infinity)

arr= [ [ [1,2,3,4],[1,2,3,4],[1,2,3,4] ],
       [ [1,2,3,4],[1,2,3,4],[1,2,3,4] ] ];
      
sum = arr.flat(Infinity).reduce((a,c)=> a+c,0);

console.log(sum);  // 60
Kamil Kiełczewski
  • 71,169
  • 26
  • 324
  • 295
5

You can try the following code:

[1, 2, 3, 4].reduce((pre,curr)=>pre+curr,0)
4

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

Santosh
  • 927
  • 12
  • 11
  • Totally agree, this is the most effective way if array numbers are in sequence. Gauss & Consecutive Numbers formula var array = [1, 2, 3, 4]; var n = array.length; var sum = n/2 * (1+4) – Kirill A Aug 27 '21 at 15:10
4

You can combine reduce() method with lambda expression:

[1, 2, 3, 4].reduce((accumulator, currentValue) => accumulator + currentValue);
antonjs
  • 13,574
  • 11
  • 62
  • 91
4

With reduce()

[1, 2, 3, 4].reduce((a, b) => a + b, 0); // 10

With forEach()

let sum = 0;
[1, 2, 3, 4].forEach(n => sum += n);
sum; // 10

With Parameter

function arrSum(arr) { 
  sum = 0;  
  arr.forEach(n => sum += n); 
  return sum; 
}

arrSum([1, 2, 3, 4]) // 10
Ahmad Moghazi
  • 983
  • 10
  • 12
3

i saw all answers going for 'reduce' solution

var array = [1,2,3,4]
var total = 0
for (var i = 0; i < array.length; i++) {
    total += array[i]
}
console.log(total)
Adrian Swifter
  • 79
  • 1
  • 1
  • 9
3

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);
bahri noredine
  • 681
  • 8
  • 15
3

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)
Shoaib Khalil
  • 944
  • 7
  • 8
2

Cool tricks here, I've got a nit pick with a lot of the safe traditional answers not caching the length of the array.

function arraySum(array){
  var total = 0,
      len = array.length;

  for (var i = 0; i < len; i++){
    total += array[i];
  }

  return total;
};

var my_array = [1,2,3,4];

// Returns 10
console.log( arraySum( my_array ) );

Without caching the length of the array the JS compiler needs to go through the array with every iteration of the loop to calculate the length, it's unnecessary overhead in most cases. V8 and a lot of modern browsers optimize this for us, so it is less of a concern then it was, but there are older devices that benefit from this simple caching.

If the length is subject to change, caching's that could cause some unexpected side effects if you're unaware of why you're caching the length, but for a reusable function who's only purpose is to take an array and add the values together it's a great fit.

Here's a CodePen link for this arraySum function. http://codepen.io/brandonbrule/pen/ZGEJyV

It's possible this is an outdated mindset that's stuck with me, but I don't see a disadvantage to using it in this context.

  • The issue of caching the length is a red herring. JS engines will optimize this for you without blinking. –  Jan 10 '16 at 17:06
2
Object.defineProperty(Object.prototype, 'sum', {
    enumerable:false,
    value:function() {
        var t=0;for(var i in this)
            if (!isNaN(this[i]))
                t+=this[i];
        return t;
    }
});

[20,25,27.1].sum()                 // 72.1
[10,"forty-two",23].sum()          // 33
[Math.PI,0,-1,1].sum()             // 3.141592653589793
[Math.PI,Math.E,-1000000000].sum() // -999999994.1401255

o = {a:1,b:31,c:"roffelz",someOtherProperty:21.52}
console.log(o.sum());              // 53.519999999999996
ostranenie
  • 37
  • 2
  • Does this code remove your operating system? Or does it send your personal information to me? –  Sep 09 '17 at 12:21
2

This is much easier

function sumArray(arr) {
    var total = 0;
    arr.forEach(function(element){
        total += element;
    })
    return total;
}

var sum = sumArray([1,2,3,4])

console.log(sum)
2

With ES6 rest parameter

let array = [1, 2, 3, 4]

function sum(...numbers) {
    let total = 0;
    for (const number of numbers) {
        total += number;
    }
    return total;
}

console.log(sum(...array));
cdavis
  • 111
  • 5
  • Note that given a large array this will give stack overflow exceptions (spread operator in general is can result in this with large inputs) – Colin D Nov 02 '19 at 03:36
2

A simple method example:

function add(array){
    var arraylength = array.length;
    var sum = 0;
    for(var timesToMultiply = 0; timesToMultiply<arraylength; timesToMultiply++){
        sum += array[timesToMultiply];
    }

    return sum;
}

console.log(add([1, 2, 3, 4]));
Dennis Vash
  • 42,190
  • 6
  • 81
  • 99
2

When the array consists of strings one has to alter the code. This can be the case, if the array is a result from a databank request. This code works:

alert(
["1", "2", "3", "4"].reduce((a, b) => Number(a) + Number(b), 0)
);

Here, ["1", "2", "3", "4"] ist the string array and the function Number() converts the strings to numbers.

feli_x
  • 127
  • 8
2

Is there a reason not to just filter the array first to remove non-numbers? Seems simple enough:

[1, 2, 3, null, 'a'].filter((x) => !isNaN(x)).reduce((a, b) => a + b)
Morrious
  • 118
  • 7
1

try this...

function arrSum(arr){
    total = 0;  
    arr.forEach(function(key){
        total = total + key;            
    });
    return total;
}
Sushil
  • 1,968
  • 21
  • 24
1

Vanilla JavaScript is all you need:

> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; a.forEach(function(e){sum += e}); sum
10
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; a.forEach(e => sum += e); sum
10
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; for(e in a) sum += e; sum
"00123foobar"
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; for(e of a) sum += e; sum
10
Cees Timmerman
  • 15,267
  • 10
  • 85
  • 116
1

This function can sum up all the numbers -

 function array(arr){
   var sum = 0;
   for (var i = 0; i< arr.length; i++){
    sum += arr[i];
   }
   console.log(sum);
 }
 array([5, 1, 3, 3])
MRIDUAVA
  • 71
  • 4
1

Considering you have the array

const arr = [1, 2, 3, 4];

For me, the most intuitive way is using a for-in

let sum = 0;
for(var value in arr) {
    sum += arr[value];
}

console.log('Array:', arr);
console.log('Sum:', sum);

Yet, you can also use Arrow Functions and the reduce function

const sum = arr.reduce(function (a, b) {
    return a + b;
}, 0);

console.log('Array:', arr);
console.log('Sum:', sum);

They're both gonna output

Array: [ 1, 2, 3, 4]
Sum: 10
Tiago Martins Peres
  • 12,598
  • 15
  • 77
  • 116
1
getTotal = (arr) => {
    let total = 0
    for (let i = 0; i < arr.length; i++) {
        total += arr[i];
    }
    return total
}

getTotal([1, 2, 3, 4]) // 10
getTotal([1, 2, 3, 4, 5]) // 15

Sharjeel Faiq
  • 57
  • 1
  • 9
0

Just use this function:

function sum(pArray)
{
  pArray = pArray.reduce(function (a, b) {
      return a + b;
  }, 0);

  return pArray;
}

function sum(pArray)
{
  pArray = pArray.reduce(function (a, b) {
      return a + b;
  }, 0);

  return pArray;
}

var arr = [1, 4, 5];

console.log(sum(arr));
Black
  • 15,426
  • 32
  • 140
  • 232
0

A "duplicate" question asked how to do this for a two-dimensional array, so this is a simple adaptation to answer that question. (The difference is only the six characters [2], 0, which finds the third item in each subarray and passes an initial value of zero):

const twoDimensionalArray = [
  [10, 10, 1],
  [10, 10, 2],
  [10, 10, 3],
];
const sum = twoDimensionalArray.reduce( (partial_sum, a) => partial_sum + a[2], 0 ) ; 
console.log(sum); // 6
Cat
  • 4,016
  • 2
  • 7
  • 17
0

You can try this:

var arr = [100,114,250,1200];
var total = 0; 
for(var i in arr){
  total += parseInt(arr[i]);
}

console.log(total);

Output will be: 1664

Or if value is Float, then try this:

var arr = [100.00,114.50,250.75,1200.00];
    var total = 0; 
    for(var i in arr){
      total += parseFloat(arr[i]);
    }
    
    console.log(total.toFixed(2));

Output will be: 1665.25

Faridul Khan
  • 1,387
  • 1
  • 13
  • 26
0

I´m aware that this is an old post. But I just wanted to share my approach to the problem.

let myArr = [1, 3, 4, 5, 6, 7, 8];
let counter = 0;
for(let i = 0; i < myArr.length; i++){
  counter = counter + myArr[i];
    console.log(counter);}
Robert CG
  • 19
  • 6
0
//Try this way

const arr = [10,10,20,60]; 
const sumOfArr = (a) =>{
    let sum=0;
    for(let i in a) { 
        sum += a[i];
    }
    return sum;
}
console.log(sumOfArr(arr))
Force Bolt
  • 883
  • 7
  • 7
0

The truth is there is an old and funny classic solution (beside newbie 'foreach' and 'reduce'): the classic for of.

y = 0;
for (x of [1, 2, 3, 4]) y+=x;
Mityu
  • 59
  • 1
  • 7
-1

Someone also can use map() function for the summation of an array values.

function sumOfArrVal(arr){
    let sum=0;
    arr.map(val=>sum+=val)
    return sum
}

let result=sumOfArrVal([1,2,3,4])
console.log(result)
  • Since map builds a new array, using it when you aren't using the returned array is an anti-pattern. In this case you should use .reduce instead – Ghostrydr Apr 06 '22 at 14:45
-1

No one mentioned functional programming, but it would be very clean approach to use Ramda in this case:

//Assuming you use nodejs, but can also be used in browser
const R = require('ramda');

let nums = [2, 4, 6, 8, 10];
console.log(R.sum(nums));
valerii15298
  • 618
  • 2
  • 11
-1

I see that this is an old question, but hardly any of the answers actually use jQuery and specifically $.each as requested by the asker. There is a way to do this, but the native approaches as suggested by many (i.e. using Array.reduce()) are much better and easier.

Here's the jQuery way if you absolutely have to use it:

  var arr = [1,2,3,4];
  var sum = 0;
  
  $.each( arr, (i, v) => sum += v);

  alert(sum); // This will be 10
aalaap
  • 3,888
  • 5
  • 48
  • 56
-2

Use recursion

var sum = (arr) => arr.length === 1 ? arr[0] : arr.shift() + sum(arr);
sum([1,2,3,4]) // 10
Giffo
  • 4,071
  • 3
  • 14
  • 16
-2

In addition, sum with es6 for simple array.

const sum = [1, 2, 3].reduce((partial_sum, a) => partial_sum + a,0);
 
console.log(sum); 

For object array with default initialize value

const totalAmount = obj => 
    Object.values(obj).reduce((acc, { order_qty, mrp_price }) => 
    acc + order_qty * mrp_price, 0);
    
    console.log(totalAmount); 
Majedur
  • 2,402
  • 1
  • 24
  • 34
-3

For really large numbers cycling or reducing could be process intensive. What about using Gauss?

sum = (n * (n+1))/2;

From mathcentral.

cramopy
  • 3,393
  • 5
  • 26
  • 42
MangoHeat
  • 1
  • 3
  • 1
    This only works for sequential arrays starting at 1, with a step of 1. Granted, the OPs question includes an example which may be confusing, since [1, 2, 3, 4] fits the bill. But what if we want to sum this one: [1, 7, 21, 10009, 300198] ? – Silviu Preda Jan 16 '18 at 12:40
-5
    <!DOCTYPE html>
    <html>
    <body>

      <p>Click the button to join two arrays.</p>
      <button onclick="myFunction()">Try it</button>
      <p id="demo"></p>
    <script>
var hege = [1, 2,4,6,7,8,8];
var stale = [1, 2,4,5];
function myFunction() {
    console.log((hege.length > stale.length))    
    var children  = (hege.length > stale.length)? abc1() :abc2();       document.getElementById("demo").innerHTML = children;
}
function abc1(){
    console.log(hege,"Abc1")    
    var abcd=hege.map(function (num, idx) {
        console.log(hege.length , idx)
        return stale.length>idx?num + stale[idx]:num;
    })
    return abcd;
}

function abc2(){

    console.log(hege,"Abc2",stale)    
    var abcd=stale.map(function (num, idx) {
        console.log(hege.length , idx)
        return hege.length>idx?num + hege[idx]:num;
    })
    return abcd;
}
</script>

</body>
</html>
-12

Use map:

var sum = 0;
arr.map(function(item){
    sum += item;
});

// sum now contains the total.

You could potentially add the method to the Array prototype.

Array.prototype.sum = function(){
    var sum = 0;
    this.map(function(item){
        sum += item;
    });
    return sum;
}

Then you can use it on any Array like so:

arr.sum();
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Capstone
  • 2,178
  • 2
  • 19
  • 38
  • 27
    That's because it's _wrong_ to use _map_ in this case. map _maps_ array elements somewhere, what you're looking for if you want to be functional is _reduce_ – Benjamin Gruenbaum May 07 '13 at 03:25
  • Who said anything about being functional? Or do you mean functional in the sense of being useful? – Capstone May 07 '13 at 04:58
  • 14
    `forEach` should be used instead of `map` in this case. – Oleg May 25 '13 at 16:09
  • 2
    Extending the prototype of built-in objects is bad in my opinion. Use a separate utility class for methods like these or some other method. – oldwizard Oct 15 '15 at 10:43
  • At this point I think the realistic answers have been added above, but I think this is useful for completeness ;) It's still better than the accepted answer. Of course you could also extend the prototype of jQuery, just for fun. – MrMowgli Jan 07 '16 at 10:54
  • 2
    You're using `map()` improperly. It's supposed to be used to generate a new array from an existing array... and that's exactly what it's doing in this case. It's instantiating and returning an entirely unnecessary array, populated with `undefined`. On top of that, you've polluted `Array.prototype` with another enumerable property. The array methods `map`, `forEach`, `filter`, `reduce`, `some`, etc are built with specific purposes in mind. While this may "function" it's ridiculously inefficient because it's doing unnecessary work... because you've selected the inappropriate method. – canon Jan 07 '16 at 14:56
  • Vote down means "wrong", this is not a wrong answer. If you don't like an answer, feel free to comment but if it's really bad it won't get enough vote ups. Vote down is a strong negative, that's why StackOverflow will give you negative points when you vote down, so please use them carefully. – Kamil Kiełczewski Sep 19 '19 at 07:09