Reputation: 31285
I was reading an article here
reduce
combines an array into a single value by repeatedly using a function that combines an element of the array with a base value. This is exactly what sum did, so it can be made shorter by using reduce... except that addition is an operator and not a function in JavaScript, so we first had to put it into a function.
function reduce(combine, base, array) {
forEach(array, function (element) {
base = combine(base, element);
});
return base;
}
function add(a, b) {
return a + b;
}
function sum(numbers) {
return reduce(add, 0, numbers);
}
function countZeroes(array) {
function counter(total, element) {
return total + (element === 0 ? 1 : 0);
}
return reduce(counter, 0, array);
}
reduce
combines an array into a single value? : does it mean all the elements are getting sum-med or concatinated?Upvotes: 0
Views: 2177
Reputation:
In addition to the accepted answer I want to point out that reduce
is a very generic concept. It is even more generic than map
or filter
, since you can deduce them from reduce
.
You can reduce not only primitives like Number
s, but almost everything. As an illustration I give you an example for the reduction of functions:
const inc = x => x + 1;
const sqr = x => x * x;
let fs = [inc, sqr];
fs.reduce((f, g) => g(f), 2); // 9
This is just function composition. Hence we can utilize reduce to compose functions.
Upvotes: 2
Reputation: 522402
A reduce operation works by iterating over the array and presenting an accumulator to a custom callback. That callback is free to do with that accumulator whatever it wants. Typically the accumulator is, for example, a number that the callback adds to. So an array of numbers will be reduced to one number.
Array.prototype.reduce
is really just an abstraction over this:
var acc = 0;
for (var i = 0; i < arr.length; i++) {
acc += arr[i];
}
Expressed as reduction:
var acc = arr.reduce(function (acc, n) {
return acc + n;
});
Obviously, you don't have to use +
, you can do anything else, like:
var acc = [];
for (var i = 0; i < arr.length; i++) {
acc.push(arr[i]);
}
var acc = arr.reduce(function (acc, n) {
acc.push(n);
return acc;
}, []);
The result is the original array, nothing has been "reduced". (Yes, this is pointless, but demonstrates the freedom you have.)
The accumulator is simply the value that that callback returned during the previous iteration. A reduction operation proceeds as:
reduce
spits out result of last callback as result of reduce operation* See API documentation for details on first iteration behaviour.
Upvotes: 2
Reputation: 339
Reduce reduces the list over a function. It is too cheap to say that it combines it into a single value, as you can reduce it to a list.
Reduce is also known as the fold construction infunctional programming languages. If you do a bit of research on fold ( https://en.wikipedia.org/wiki/Fold_(higher-order_function) ) and then try to come back, it might give more sense.
Upvotes: 1