Basics
In Javascript, it is possible to chain filter(), map() and reduce() methods and make them a single smooth chain of commands.
Typically those methods are in the order filter() -> map() -> reduce(). It is also possible to use only two of those methods.
All these methods work only with arrays (lists).
First the filter() method selects the needed elements from the list.
Then the map() method modifies the elements.
Finally reduce() method results in a single output value.
Example of Chaining
In the example below, first we have an original list of seven numbers.
Filter() method selects only the numbers below ten and puts them in a new array.
Then map() method takes this array and one by one multiplies all the numbers by 2.
Finally reduce() method sums up all numbers and we get the final result.
let originalNumbers = [1, 22, 3, 14, 5, 11, 7];
const result = () => {
return originalNumbers
.filter(e => e < 10)
.map(e => 2 * e)
.reduce((acc, curr) => acc + curr, 0);
}
console.log(result);
Code Explanation
In line 1, we define an array of numbers. This is the original array and it will not change.
In line 3, we define a new variable called result that will hold the final result. Its value will be the return value of the function in the curly brackets (lines 3 - 8).
In line 4, we define that we will use the array ”originalNumbers” for the methods in following lines.
In line 5, the filter() method will iterate through the numbers in the ”originalNumbers” array and check the numbers one by one if they are below 10 or not. If they are below 10, they will be added to a new array, otherwise they will be left out. The new array will be [1, 3, 5, 7].
In line 6, the map() method takes the first element in the new array that is 1 and multiplies it by 2. Then it adds the result 2 into the new array. After that it takes the next element 3 and multiplies it by 2 and adds it in the new array. Then it will continue and do the same to all the elements in the array and adds the results in the new array. The new array will be [2, 6, 10, 14].
In line 7, the reduce() method will iterate through the new array and sum up all the values (32). This will be the final result of the funtion.