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.
This question is related to
javascript
jquery
arrays
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
var arr = [1,2,3,4];
var total=0;
for(var i in arr) { total += arr[i]; }
With ES6 rest parameter
let array = [1, 2, 3, 4]_x000D_
_x000D_
function sum(...numbers) {_x000D_
let total = 0;_x000D_
for (const number of numbers) {_x000D_
total += number;_x000D_
}_x000D_
return total;_x000D_
}_x000D_
_x000D_
console.log(sum(...array));
_x000D_
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 = [_x000D_
[10, 10, 1],_x000D_
[10, 10, 2],_x000D_
[10, 10, 3],_x000D_
];_x000D_
const sum = twoDimensionalArray.reduce( (partial_sum, a) => partial_sum + a[2], 0 ) ; _x000D_
console.log(sum); // 6
_x000D_
Just use this function:
function sum(pArray)
{
pArray = pArray.reduce(function (a, b) {
return a + b;
}, 0);
return pArray;
}
function sum(pArray)_x000D_
{_x000D_
pArray = pArray.reduce(function (a, b) {_x000D_
return a + b;_x000D_
}, 0);_x000D_
_x000D_
return pArray;_x000D_
}_x000D_
_x000D_
var arr = [1, 4, 5];_x000D_
_x000D_
console.log(sum(arr));
_x000D_
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])
You can combine reduce() method with lambda expression:
[1, 2, 3, 4].reduce((accumulator, currentValue) => accumulator + currentValue);
If you happen to be using Lodash you can use the sum function
array = [1, 2, 3, 4];
sum = _.sum(array); // sum == 10
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.
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
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.
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]_x000D_
_x000D_
sum = arr.reduce((a,c)=>a+c,0)_x000D_
sortSum = [...arr].sort((a,b)=>a-b).reduce((a,c)=>a+c,0)_x000D_
_x000D_
console.log('sum: ',sum);_x000D_
console.log('sortSum:',sortSum);_x000D_
console.log('sum==sortSum :', sum==sortSum);_x000D_
_x000D_
// we use .sort((a,b)=>a-b) instead .sort() because_x000D_
// that second one treat elements like strings (so in wrong way)_x000D_
// e.g [1,10,9,20,93].sort() --> [1, 10, 20, 9, 93]
_x000D_
For multidimensional array of numbers use arr.flat(Infinity)
arr= [ [ [1,2,3,4],[1,2,3,4],[1,2,3,4] ],_x000D_
[ [1,2,3,4],[1,2,3,4],[1,2,3,4] ] ];_x000D_
_x000D_
sum = arr.flat(Infinity).reduce((a,c)=> a+c,0);_x000D_
_x000D_
console.log(sum); // 60
_x000D_
Use recursion
var sum = (arr) => arr.length === 1 ? arr[0] : arr.shift() + sum(arr);
sum([1,2,3,4]) // 10
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);
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.
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
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]));
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;
}
arr.reduce(function (a, b) {
return a + b;
});
Reference: Array.prototype.reduce()
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.
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
For really large numbers cycling or reducing could be process intensive. What about using Gauss?
sum = (n * (n+1))/2;
From mathcentral.
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
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.
<!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>
Anyone looking for a functional oneliner like me? Take this:
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);
Use reduce
let arr = [1, 2, 3, 4];_x000D_
_x000D_
let sum = arr.reduce((v, i) => (v + i));_x000D_
_x000D_
console.log(sum);
_x000D_
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.
let total = 0;
for (let value of [1,2,3,4]) {
total += value;
}
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)
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)
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)
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
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
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();
// Given array 'arr'
var i = arr.length;
var sum = 0;
while (--i) sum += arr[i];
This will take on average 1.57 ms/run (measured over 1000 runs on an array of 100 random normal numbers), compared to 3.604 ms/run with the eval()
method above and 2.151 ms/run with a standard for(i,length,++) loop.
Methodology note: this test was run on a Google Apps Script server, so their javascript engines are pretty much the same as Chrome.
EDIT: --i
instead of i--
saves 0.12 ms each run (i-- is 1.7)
EDIT: Holy expletive, never mind this whole post. Use the reduce() method mentioned above, it's only 1 ms/run.
var total = 0;
$.each(arr,function() {
total += this;
});
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.
In Lisp, this'd be exactly the job for reduce
. You'd see this kind of code:
(reduce #'+ '(1 2 3)) ; 6
Fortunately, in JavaScript, we also have reduce
! Unfortunately, +
is an operator, not a function. But we can make it pretty! Here, look:
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? :-)
Even better! If you're using ECMAScript 2015 (aka ECMAScript 6), it can be this pretty:
const sum = [1, 2, 3].reduce((partial_sum, a) => partial_sum + a,0);
console.log(sum); // 6
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...
Funny approach:
eval([1,2,3].join("+"))
try this...
function arrSum(arr){
total = 0;
arr.forEach(function(key){
total = total + key;
});
return total;
}
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
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);
Source: Stackoverflow.com