1. What is reduce
reduce
Methods are one of the important methods of arrays in JavaScript, which are used to perform cumulative calculations on elements in arrays. It receives a callback function as an argument and returns a final calculation result.reduce
It is very useful in many scenarios, such as summing, array flattening, object counting, data conversion, etc.
2. Reduce syntax
2.1 Syntax
(callback, initialValue)
2.2 Parameter description
-
callback(accumulator, currentValue, currentIndex, array)
: Callback function, accepting four parameters:-
accumulator
: Last timecallback
Return value after execution -
currentValue
: Current value -
currentIndex
: The index of the current element in the array -
array
: Original array (array being traversed)
-
-
initialValue
(Optional): The initial value of the accumulator- If provided, the accumulator starts with initialValue
- If not provided, take the first element of the array
3. Reduce execution process
3.1 Execution process
reduce
The method will iterate over each element of the array and apply a callback function to it. The execution process is as follows:
- Initialization
accumulator
: If providedinitialValue
,butaccumulator
PickinitialValue
, otherwise take the first element of the array and skip that element. - Iterate through the array: from index 0 (if there is
initialValue
) or 1 (if notinitialValue
) Start, execute callback in turn, and updateaccumulator
。 - Return to the final
accumulator
Value.
3.2 Example
const numbers = [1, 2, 3, 4]; const result = ((acc, cur, index) => { (`accumulator: ${acc}, Current value: ${cur}, index: ${index}`); return acc + cur; }, 0); ('The final result:', result);
The execution results are as follows:
Accumulator: 0, current value: 1, index: 0
Accumulator: 1, current value: 2, index: 1
Accumulator: 3, current value: 3, index: 2
Accumulator: 6, Current value: 4, Index: 3
Final result: 10
4. Reduce usage scenarios
4.1 Array summation
const numbers = [1, 2, 3, 4, 5]; const sum = ((acc, cur) => acc + cur, 0); (sum); // Output 15
4.2 Statistics the number of times an element appears in the array
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']; const count = ((acc, fruit) => { acc[fruit] = (acc[fruit] || 0) + 1; return acc; }, {}); (count); // { apple: 3, banana: 2, orange: 1 }
4.3 Calculate the sum of certain attributes of objects in an array
const products = [ { name: 'Laptop', price: 1000 }, { name: 'Phone', price: 500 }, { name: 'Tablet', price: 300 } ]; const totalPrice = ((acc, product) => acc + , 0); (totalPrice); // Output 1800
5. Advanced usage of reduce
5.1 Group data by attributes
const people = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 25 }, { name: 'David', age: 30 } ]; const groupedByAge = ((acc, person) => { (acc[] = acc[] || []).push(person); return acc; }, {}); (groupedByAge); // Output:// { // 25: [{ name: 'Alice', age: 25 }, { name: 'Charlie', age: 25 }], // 30: [{ name: 'Bob', age: 30 }, { name: 'David', age: 30 }] // }
5.2 Calculate the sum of nested objects
const orders = [ { customer: 'Alice', total: 50 }, { customer: 'Bob', total: 30 }, { customer: 'Alice', total: 20 } ]; const customerTotals = ((acc, order) => { acc[] = (acc[] || 0) + ; return acc; }, {}); (customerTotals); // Output: { Alice: 70, Bob: 30 }
5.3 Combining multiple reduces for complex calculations
const data = [ { category: 'A', value: 10 }, { category: 'B', value: 20 }, { category: 'A', value: 15 }, { category: 'B', value: 25 } ]; const aggregatedData = ((acc, item) => { acc[] = (acc[] || []).concat(); return acc; }, {}); const summedData = (aggregatedData).reduce((acc, key) => { acc[key] = aggregatedData[key].reduce((sum, num) => sum + num, 0); return acc; }, {}); (summedData); // Output: { A: 25, B: 45 }
6. Handwritten reduce implementation
= function(callback,initialValue){ const arr = this; // Get the array calling reduce if(typeof callback !== "function"){ // Verify that the callback function is passed in throw new TypeError(`${callback} is not a function`); } let accumulator; // Accumulator let startIndex; // Array traversal start position if(initialValue!==undefined){ // Determine whether the initial value has been passed accumulator = initialValue; startIndex = 0; }else{ // If no initial value is provided, the first array element is used as the initial value of the accumulator if(===0){ throw new TypeError(`Reduce of empty array with on initial value`); } accumulator = arr[0]; startIndex = 1; } // Iterate through the array and apply the callback function for(let i=startIndex;i<;i++){ accumulator = callback(accumulator,arr[i],i,arr); } // Return the accumulated result return accumulator } const numbers = [1,2,3,4,5]; const sum = ((acc,curr)=>acc+curr,0) // 15 const product = ((acc,curr)=>acc*curr) // 120
Summarize
This is the article about the execution process, usage scenarios and advanced usage of reduce methods in JavaScript. For more related contents of reduce methods in JS, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!