Definition:
Reduce is a higher-order array method that applies a callback function to each element of an array to reduce it to a single value.
Practical Steps:
- Create an array: Define an array of elements you want to reduce.
- Define a callback function: Write a function that takes two parameters: the accumulator (result of previous iteration) and current element.
- Call reduce(callback, initialValue):
- Callback: The function that performs the operation on each element.
- Initial value (optional): The starting point for the accumulation (if not provided, the first element of the array is used).
- Iteration: The callback function is applied to each element in the array. The accumulator is updated with the result of the callback.
- Return value: The final accumulator value is returned.
Key Concepts:
- Callback function: A function that operates on each element of the array.
- Initial value: An optional starting point for the accumulation.
- Does not modify original array: Reduce does not change the original array, it only returns the accumulated value.
JavaScript Example:
// Calculate the total sum of an array of numbers
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, current) => accumulator + current);
// sum will be 15