javascript sum of array
const sum = arr => arr.reduce((a, b) => a + b, 0);
javascript sum of array
const sum = arr => arr.reduce((a, b) => a + b, 0);
reduce javascript
/* this is our initial value i.e. the starting point*/
const initialValue = 0;
/* numbers array */
const numbers = [5, 10, 15];
/* reducer method that takes in the accumulator and next item */
const reducer = (accumulator, item) => {
return accumulator + item;
};
/* we give the reduce method our reducer function
and our initial value */
const total = numbers.reduce(reducer, initialValue)
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