reduce() method takes two arguments and returns one result for the whole array. It iterates over all values beginning from the left and takes the current value and the result from the previous run.
The far best way to understand the reducer is to calculate the sum of an array full of integer values. The following example takes 10 and adds 20, then it takes 30 and adds 30, then it takes 60 and add 40 and finally, it takes 100 and adds 50 to then return 150. If you do not provide a initialValue for the first run, previousValue will be set to the first element.
const numbers = [10, 20, 30, 40, 50]; const result = numbers.reduce((previousValue, currentValue) => previousValue + currentValue); console.log(result); // 150
reduce()method does work with any object, and it is not limited to numbers. You can concatenate strings or work with complex objects as well.
const texts = ["Hello", "my", "friend", "!"]; const result = texts.reduce((previousValue, currentValue) => previousValue + " " + currentValue); console.log(result); // Hello my friend !
The reduce operator supports a callback function with multiple parameters.
reduce(function callbackFn(previousValue, currentValue, currentIndex, array)
The callback function takes up to four arguments.
- previousValue (the result of the previous callback function).
- currentValue (the value of the current item in the array)
- currentIndex [optional] (the value of the current array index)
- array [optional] (optional: the array to traverse)
You can set the value of the first iteration, otherwise the first previousValue is not initialized.
Find out more here.