Reputation: 41614
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.
Upvotes: 1623
Views: 3086924
Reputation: 287
// 1:
const numbers = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9);
// Or const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let sum = numbers.reduce(
(accumulator, currentValue) => accumulator + currentValue
);
console.log(sum);
// 2:
sum = 0;
for (const number of numbers) {
sum += number;
}
console.log(sum);
// 3:
sum = 0;
for (const index in numbers) {
sum += numbers[index];
}
console.log(sum);
// 4:
sum = 0;
for (let index = 0; index < numbers.length; index++) {
sum += numbers[index];
}
console.log(sum);
// 5:
sum = 0;
numbers.forEach((num) => (sum += num));
console.log(sum);
// ;)
Upvotes: 0
Reputation: 480
const a = [1,'2',3,100,'200','text'];
var total= 0;
let b = a.filter( value => !Number.isNaN(Number(value)) );
for(let c in b)
{
total += Number(b[c]);
}
console.log(total)
//output:306
Upvotes: 0
Reputation: 60707
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? :-)
Upvotes: 1782
Reputation: 1015
You can get the sum using for of loop like following:
let arr = [1, 2, 3, 4];
let total = 0;
for (let i of arr) {
total += i;
}
console.log(total)
Upvotes: 2
Reputation: 37
i think this is the simple way to find sum array of numbers
function sumArray(arr){
let total = 0;
for(i = 0; i<arr.length ; i++){
total += arr[i];
}
return total;
}
console.log(sumArray([1,2,3,4,]));
Upvotes: 0
Reputation: 889
If you care about performance, define a function that uses a for
-loop.
function sum(arr) {
var res = 0;
for (var x of arr) {
res += x;
}
return res;
}
I benchmarked a selection of implementations using benchmark.js
(typescript version):
const arr = Array.from({ length: 100 }, () => Math.random());
const reducer = function (p: number, a: number) {
return p + a;
};
const recursion = function (arr: number[], i: number) {
if(i > 0) return arr[i] + recursion(arr, i - 1)
else return 0
};
const recursion2 = function (arr: number[], i: number, len: number) {
if(i < len) return arr[i] + recursion2(arr, i + 1, len)
else return 0
};
const recursion3 = function (arr: number[], i: number) {
if(i < arr.length) return arr[i] + recursion3(arr, i + 1)
else return 0
};
new Benchmark.Suite()
.add("jquery", () => {
let res = 0;
$.each(arr, (_, x) => (res += x));
})
.add("lodash", ()=>_.sum(arr))
.add("forEach", () => {
let res = 0;
arr.forEach((x) => (res += x));
})
.add("reduce", () => arr.reduce((p, a) => p + a, 0))
.add("predefined reduce", () => arr.reduce(reducer, 0))
.add("eval", () => eval(arr.join("+")))
.add("recursion", () => recursion(arr, arr.length - 1))
.add("recursion2", () => recursion2(arr, 0, arr.length))
.add("recursion3", () => recursion3(arr, 0))
.add("naive", () => (
arr[0]+arr[1]+arr[2]+arr[3]+arr[4]+arr[5]+arr[6]+arr[7]+arr[8]+arr[9]+
arr[10]+arr[11]+arr[12]+arr[13]+arr[14]+arr[15]+arr[16]+arr[17]+arr[18]+arr[19]+
arr[20]+arr[21]+arr[22]+arr[23]+arr[24]+arr[25]+arr[26]+arr[27]+arr[28]+arr[29]+
arr[30]+arr[31]+arr[32]+arr[33]+arr[34]+arr[35]+arr[36]+arr[37]+arr[38]+arr[39]+
arr[40]+arr[41]+arr[42]+arr[43]+arr[44]+arr[45]+arr[46]+arr[47]+arr[48]+arr[49]+
arr[50]+arr[51]+arr[52]+arr[53]+arr[54]+arr[55]+arr[56]+arr[57]+arr[58]+arr[59]+
arr[60]+arr[61]+arr[62]+arr[63]+arr[64]+arr[65]+arr[66]+arr[67]+arr[68]+arr[69]+
arr[70]+arr[71]+arr[72]+arr[73]+arr[74]+arr[75]+arr[76]+arr[77]+arr[78]+arr[79]+
arr[80]+arr[81]+arr[82]+arr[83]+arr[84]+arr[85]+arr[86]+arr[87]+arr[88]+arr[89]+
arr[90]+arr[91]+arr[92]+arr[93]+arr[94]+arr[95]+arr[96]+arr[97]+arr[98]+arr[99]))
.add("loop with iterator", () => {
let res = 0;
for (const x of arr) res += x;
})
.add("traditional for loop", () => {
let res = 0;
// cache the length in case the browser can't do it automatically
const len = arr.length;
for (let i = 0; i < len; i++) res += arr[i];
})
.add("while loop", () => {
let res = 0;
let i = arr.length;
while (i--) res += arr[i];
})
.add("loop in a function ", () => sum(arr))
.on("cycle", (event) => console.log(String(event.target)))
.run();
In chrome 104, the for
-loop-based implementations are the fastest:
jquery x 1,832,472 ops/sec ±1.35% (61 runs sampled)
lodash x 2,079,009 ops/sec ±1.11% (68 runs sampled)
forEach x 4,887,484 ops/sec ±2.35% (67 runs sampled)
reduce x 21,762,391 ops/sec ±0.46% (69 runs sampled)
predefined reduce x 2,026,411 ops/sec ±0.50% (68 runs sampled)
eval x 33,381 ops/sec ±2.54% (66 runs sampled)
recursion x 2,252,353 ops/sec ±2.13% (62 runs sampled)
recursion2 x 2,301,516 ops/sec ±1.15% (65 runs sampled)
recursion3 x 2,395,563 ops/sec ±1.65% (66 runs sampled)
naive x 31,244,240 ops/sec ±0.76% (66 runs sampled)
loop with iterator x 29,554,762 ops/sec ±1.07% (66 runs sampled)
traditional for loop x 30,052,685 ops/sec ±0.67% (66 runs sampled)
while loop x 18,624,045 ops/sec ±0.17% (69 runs sampled)
loop in a function x 29,437,954 ops/sec ±0.54% (66 runs sampled)
Firefox 104 shows similar behaviour:
jquery x 1,461,578 ops/sec ±1.58% (64 runs sampled)
lodash x 4,931,619 ops/sec ±0.80% (66 runs sampled)
forEach x 5,594,013 ops/sec ±0.51% (68 runs sampled)
reduce x 3,731,232 ops/sec ±0.53% (66 runs sampled)
predefined reduce x 2,633,652 ops/sec ±0.54% (66 runs sampled)
eval x 105,003 ops/sec ±0.88% (66 runs sampled)
recursion x 1,194,551 ops/sec ±0.24% (67 runs sampled)
recursion2 x 1,186,138 ops/sec ±0.20% (68 runs sampled)
recursion3 x 1,191,921 ops/sec ±0.24% (68 runs sampled)
naive x 21,610,416 ops/sec ±0.66% (66 runs sampled)
loop with iterator x 15,311,298 ops/sec ±0.43% (67 runs sampled)
traditional for loop x 15,406,772 ops/sec ±0.59% (67 runs sampled)
while loop x 11,513,234 ops/sec ±0.60% (67 runs sampled)
loop in a function x 15,417,944 ops/sec ±0.32% (68 runs sampled)
Implementations defining an anonymous function are generally slower because creating an anonymous function is a significant overhead. When running the benchmark with a large array, e.g., with length 1000 instead of 100, the difference between reduce
and the for
-loop-based implementations becomes insignificant in chrome.
Chrome's V8 engine knows how to inline simple anonymous functions in reduce
since the reduce
test case is much faster than the predefined reduce
test case. Firefox seems to try something similar but is less efficient in doing so. Non-inlined function calls are pretty slow in js since the call stack is less efficient than the call stack in compiled software.
Similar to reduce
, the forEach
- and jquery
-based implementations use anonymous functions and are relatively slow. lodash
has a specialized sum
implementation, but it is (as of v4.0.0) implemented as a special case of sumBy
, which is relatively inefficient.
eval
is the by far slowest test case. This makes sense since constructing the string using concatenations might cause several dynamic allocations (which are slow). Next, the parser has to be invoked and only then can the code be finally executed.
I've included some recursive implementations because some people on the internet claim that recursion is faster than loops in js. I can't reproduce their example - using benchmark.js
, recursion is very slow, and when using console.time
with a loop, both functions take the same time. When calculating the sum, as expected, recursion is much slower than loops, probably due to intense usage of the js call stack.
The naive implementation would be manually adding all 100 elements of the array. While being quite inconvenient, this is the fastest implementation. But, luckily, for
-loops come very close. Adding a single function call around the loop doesn't harm the performance. Therefore, you can feel free to use the utility function from above.
I have no explanation why the while
loop is slower than the for
loop. Iterating the array in reverse doesn't seem to be the problem here.
Upvotes: 21
Reputation: 4401
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
Upvotes: 0
Reputation: 153
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;
Upvotes: 0
Reputation: 19
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);}
Upvotes: 0
Reputation: 351
You can try the following code:
[1, 2, 3, 4].reduce((pre,curr)=>pre+curr,0)
Upvotes: 16
Reputation: 103
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
Upvotes: 3
Reputation: 870
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));
Upvotes: 0
Reputation: 351
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)
Upvotes: -2
Reputation: 179
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)
Upvotes: 5
Reputation: 1890
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.
Upvotes: 62
Reputation: 1705
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
Upvotes: 5
Reputation: 526463
var arr = [1, 2, 3, 4];
var total = 0;
for (var i in arr) {
total += arr[i];
}
Upvotes: 128
Reputation: 2402
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)
Upvotes: 5
Reputation: 2718
let total = 0;
for (let value of [1, 2, 3, 4]) {
total += value;
}
Upvotes: 7
Reputation: 1221
//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))
Upvotes: 0
Reputation: 751
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);
Upvotes: 3
Reputation: 3242
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);
Upvotes: -2
Reputation: 2007
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
Upvotes: 0
Reputation: 15421
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
Upvotes: 1
Reputation: 92347
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
Upvotes: 5
Reputation:
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
Upvotes: 7
Reputation: 166
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.
Upvotes: 2
Reputation: 179
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.
Upvotes: 10
Reputation: 21
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]));
Upvotes: 2
Reputation: 4226
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
Upvotes: 0