I have an array containing some values and I want to get their sum. Here is the example:
var somearray = ["20","40","80","400"];
I want to sum these values using jQuery. In this example the result would be 540.
To also handle floating point numbers:
(Older) JavaScript:
var arr = ["20.0","40.1","80.2","400.3"],
n = arr.length,
sum = 0;
while(n--)
sum += parseFloat(arr[n]) || 0;
ECMA 5.1/6:
var arr = ["20.0","40.1","80.2","400.3"],
sum = 0;
arr.forEach(function(num){sum+=parseFloat(num) || 0;});
ES6:
var sum = ["20.0","40.1","80.2","400.3"].reduce((pv,cv)=>{
return pv + (parseFloat(cv)||0);
},0);
The reduce() is available in older ECMAScript versions, the arrow function is what makes this ES6-specific.
I'm passing in 0 as the first pv
value, so I don't need parseFloat around it — it'll always hold the previous sum, which will always be numeric. Because the current value, cv
, can be non-numeric (NaN
), we use ||0
on it to skip that value in the array. This is terrific if you want to break up a sentence and get the sum of the numbers in it. Here's a more detailed example:
let num_of_fruits = `
This is a sentence where 1.25 values are oranges
and 2.5 values are apples. How many fruits are
there?
`.split(/\s/g).reduce((p,c)=>p+(parseFloat(c)||0), 0);
// num_of_fruits == 3.75
jQuery:
var arr = ["20.0","40.1","80.2","400.3"],
sum = 0;
$.each(arr,function(){sum+=parseFloat(this) || 0;});
What the above gets you:
123
or "123"
), floating point string or number ("123.4"
or 123.4
), or even text (abc
)You don't need jQuery. You can do this using a for
loop:
var total = 0;
for (var i = 0; i < someArray.length; i++) {
total += someArray[i] << 0;
}
Related:
You can use reduce
which works in all browser except IE8 and lower.
["20","40","80","400"].reduce(function(a, b) {
return parseInt(a, 10) + parseInt(b, 10);
})
Another method, if eval is safe & fast :
eval(["10","20","30","40","50"].join("+"))
If you want it to be a jquery method, you can do it like this :
$.sum = function(arr) {
var r = 0;
$.each(arr, function(i, v) {
r += +v;
});
return r;
}
and call it like this :
var sum = $.sum(["20", "40", "80", "400"]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With