OneCompiler

[JavaScript] How to find sum of all elements of an array?

I want to compute sum of all elements of an array, how can I do that in Javascript?

1 Answer

4 years ago by

You can use ES6 reduce function to sum the elements of an array

let numbers = [1,2,3,4,5];
let sum = numbers.reduce((previousValue, currentValue) => previousValue + currentValue);
console.log(sum);

Try running the code here : https://onecompiler.com/javascript/3xmzvzhdq

4 years ago by Meera