
Ans- The reduce() method in JavaScript is used to apply a function to each element in an array, resulting in a single output value. It iterates through the array and accumulates a single value by executing a provided function on each element.
Basic Syntax-
JavaScript
array.reduce(callbackFunction, initialValue)Parameters:
- callbackfuntion: It’s a fucntion that gets executed on each element of the array. It takes four arguments:
- Accumulator- The result of the pervious iteration.
- Current value- the current element being processed.
- Current index- optional: the index of the current element being processed.
- Source array- Optional, the array reduce() was called upon.
- initiaValue: An optional parameter representing the initial value or the initial value for the accumulator.
Example-
JavaScript
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 15Example-
JavaScript
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 15Example-
JavaScript
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, curr) => acc + curr);
console.log(sum); // 15Note:
- accumulator starts at 0.
- currentValue: takes each element of the array in sequence.
- reduce() method can be used for a variety of operations beyond summation, such as finding the maximum/Minium value, transforming data structure, or filtering data, the key is to define the appropriate logic within the callback function to achieve the desired result.
