I'm looking at this example of use of reduce() function.
function add(runningTotal, currentValue) {
return runningTotal + currentValue;
}
var nums = [1,2,3,4,5,6,7,8,9,10];
var sum = nums.reduce(add);
print(sum); // displays 55
Could you give show me some other examples of using reduce() - I'm not sure I fully follow how it works.
Thank you
JavaScript Array reduce()The reduce() method executes a reducer function for array element. The reduce() method returns a single value: the function's accumulated result. The reduce() method does not execute the function for empty array elements. The reduce() method does not change the original array.
Introduction to the JavaScript Array reduce() methodFirst, declare an array of three numbers 1, 2 and 3. Second, declare the sum variable and set its value to zero. Third, in the for loop, add up the elements of the numbers array to the sum variable. After the loop, the value of the sum variable is 6.
reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator.
The reduce() method executes the function for each value of the array (non-empty array) from left to right. The reduce() method has the following syntax: let arr = [];arr. reduce(callback(acc, curVal, index, src), initVal);
What reduces does is take an initialValue
, a function
with 2 essential parameters (can take more) and a list
of values. If no initialValue
is provided then it's assumed it's the first element of the list. The function is supposed to do something with the previousValue
usually used as an accumulator and the nextValue
.
So, assume you have a list of values: [1, 2, 3, 4, 5]
and the function is supposed to add the 2 parameters and an initialValue
of 0
.
First step:
0 + 1 = 1
2
3
4
5
Second step:
1 + 2 = 3
3
4
5
Third Step:
3 + 3 = 6
4
5
Fourth Step:
6 + 4 = 10
5
Fifth Step:
10 + 5 = 15 //Final value
As you can see, the input went from a list
to a single value, hence the name reduce
. In your example, there's no initialValue
(that's the second argument), so it's as if started on the second step.
You can also use reduce to do things like generate some kind of stream cipher.
var plaintext = "thisisaplaintext";
var chars = plaintext.split('');
var result = '';
function encrypt(runningTotal, currentValue){
var newVal = ((runningTotal + (""+runningTotal).charCodeAt()-32) % 94)+32
result = result + String.fromCharCode(newVal)
return newVal;
}
chars.reduce(encrypt, 15 /*any arbitrary starting value*/);
console.log(result);
Basically, anything that can be made with a combination of independent calculations or anything that requires some rolling total. It's nothing that you couldn't already do with a for loop, but it looks cleaner.
reduce()
works by iterating over an array and calling a reductor function (this function is the first argument passed to reduce()
. This function has four arguments:
previousValue
, which is sort of a 'running total'. this is initially undefined, unless you provide a seed value as the second argument to reduce()
.currentValue
which is an object in your arrayindex
of the current value in your arrayarray
, the array itselfwhen your reductor function is called, its return value becomes the new previousValue
argument for next time the reductor function is called. that's the magic. after the reductor function is called and given the very last object in the array, its return value will be the return value of reduce()
.
honestly, a lot of the examples you'll see (like using reduce()
to sum up a bunch of integers) are pretty easy to do with a for()
loop. its real value is when you're doing functional programming.
You can set second argument for reduce
function add(runningTotal, currentValue) {
return runningTotal + currentValue;
}
var someInitValue = 10
var nums = [1,2,3,4,5,6,7,8,9,10];
var sum = nums.reduce(add, someInitValue);
console.log(sum); // displays 65
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With