Working as a frontend developer, you will eventually stumble upon the reduce function. A built in method that is executing a reducer function on each element of an array which will result in 1 single output value.
The name Reducer can be a confusing word to begin with. We can’t at first sight associate the name to a real world example like for example the filter method. It should just be understood as reducing a collection of items into a single value. That’s it.
Trying to explain the reduce function in simple terms. You have a collection of items and you want to “reduce” it into a single value. Every time we are reducing the collection we use a “reducer”.
Let’s say we have a collection consisting of 6 characters like my name “Kasper”.
const name = ['K', 'A', 'S', 'P', 'E', 'R'];
Our job as a developer is to concat all the characters into a string which we can pass to a variable or object we later need. The issue is that all the characters is in uppercase, but we want them to be in lowercase, therefore we cannot use the Array.prototype.join method.
One way is to map over each item in the array, convert it to lowercase letter and then append to an empty string, but then we are relying on variable outside the method, which does not make it a pure function.
The reduce function makes this quit simple.
const name = ['K', 'A', 'S', 'P', 'E', 'R']; const toLowerCaseNameReducer = (accumulator, value) => accumulator += value.toLowerCase(); const newName = name.reduce(toLowerCaseNameReducer, "");
Here we pass the toLowerCaseNameReducer to the reduce function, and set the initial value to be an empty string. The reducer function has 2 parameters. 1 parameter is the accumulator.
The accumulator contains the accumulated values, which means every time we are iterating over the array, the accumulator keeps building up the string with new characters from each iteration. First iteration the accumulator is empty and then we add the value K to the string after we have turned it into a lowercase k.
Next iteration we take the existing accumulator k and add the value a to it. Third iteration we take the value s and append it to ka. and so forth until we have iterated over all the elements and will return the accumulating value which is kasper.
Another example is when you want to sum the values in an array. You can easily do that with the reduce method to.
const differentAges = [10, 4, 2, 1, 4, 5]; const sumAge = differentAges.reduce((acc, val) => acc += val, 0);
Here you should be aware of the initial value. In this example 0 is the initial value since the initial age is 0. If we provided a string, then we will keep appending a number to a string, which will result in the value “1042145” instead of 26.
The third parameter of the reduce function is the index and the fourth parameter is the array itself in case you need access the reducing array or the index.