js sum of array
[1, 2, 3, 4].reduce((a, b) => a + b, 0)
// Output: 10
js sum of array
[1, 2, 3, 4].reduce((a, b) => a + b, 0)
// Output: 10
add all elements in array javascript
console.log(
[1, 2, 3, 4].reduce((a, b) => a + b, 0)
)
console.log(
[].reduce((a, b) => a + b, 0)
)
javascript sum of array
const sum = arr => arr.reduce((a, b) => a + b, 0);
reduce method javascript
// Reduce() method executes a callback function that is passed in
// on each element of the array, resulting in single output value.
const array1 = [1, 2, 3, 4];
const callback = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(callback));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(callback, 5));
// expected output: 15 because the initial value is 5.
// This is how Reduce works.
// This is a myReduce method which takes a callback and an optional argument
// of a default accumulator. If myReduce only receives one argument, then
// myReduce will use the first element as the accumulator.
Array.prototype.myReduce = function(callback, acc) {
if (!acc) {
acc = this.shift();
}
this.forEach(function(element) {
acc = callback(acc, element)
})
return acc;
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us