In JavaScript, the reduce() method is used to reduce an array of values into a single value by repeatedly applying a function on the array’s members. It accepts two arguments: a callback function and a value to be used as an initialization parameter.
The callback function accepts four parameters:
- Accumulator: The accumulator is the initial parameter of the callback function, and it holds the collected result of the previous function calls. If no initial value is supplied, it is initialized to the first entry in the array.
- Current value: The callback function’s second parameter is the array’s current value.
- Current index: The callback function’s third parameter is the index of the current value being processed.
- An array of sources: The original array is the callback function’s fourth parameter.
The reduce() method’s aim is to conduct a custom operation on an array of items and return a single result. This can be any function that accepts two arguments: the current accumulator value and the current array value.
Here’s an example of how to use reduce() to find the sum of an array of numbers:
const number = [10, 12, 53, 14, 45]; const sum = number.reduce(function(a, b) { return a + b; }); console.log(sum); // Output: 134
The reduce() function is invoked on the numbers array with a starting value of 0. The callback function accepts two arguments: the accumulator, which starts at zero, and the array’s current value. The function adds the current value to the accumulator and returns the new accumulator value, which is used as the input for the function’s next iteration. The total of all the integers in the array is the final result.
Reduce() may also be used to discover the maximum or lowest value in an array, count the number of repetitions of a value, flatten nested arrays, and more.
By giving a callback function as a parameter to the reduce method, you may use it on an array of strings.
Here’s an example of how to concatenate all the strings in an array into a single string using reduce:
const string = ['Hello', ' ', 'world', '!']; const result = string.reduce((a, b) => { return a + b; }, ''); console.log(result); // Output: 'Hello world!'
In this example, we begin with an empty string ” as the accumulator’s first value. Then, on each iteration, we concatenate the array’s current value with the accumulator. Finally, the result is the sum of all the strings in the array.