The next-generation blog, news, and article for you to start sharing your stories today!
Threre are mostly many way to find sum of all int element of the array in javascript. we will basically use two ways.
let considered you have an array in javascript
let a = [10, 20, -30, 5, 7]
let total = 0;
for (const ele of a) { // where a is [10, 20, -30, 5, 7]
total += ele
}
// total will be 12
Now in this case we will use reduce function which is introduce in es6
let a = [10, 20, -30, 5, 7]
let sum = a.reduce((a, b) => a + b , 0)
// example like this
reduce((previousValue, currentValue) => { /* ... */ } )
For more details about javascript reduce function
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
Thank you. Please contact me in case of any query.
Vikram Parihar is an senior software engineer. He is working since 2013 in web development technologies. He works in NodeJS, Angular, Vue, PHP, Laravel, Express JS and various popular technologies.