How to use .reduce() method in Javascript
By Tan Lee Published on Dec 18, 2024 167
It takes a callback function as its first parameter and an optional initial value as its second parameter. The callback function is applied to each element of the array to calculate the final result.
The callback function in .reduce()
receives two parameters: an accumulator and the current value. The accumulator stores the intermediate result of the reduction, while the current value represents the current element being processed. The callback function performs operations on these values and returns the updated accumulator.
Here is an example usage of the .reduce()
method:
const numbers = [1, 2, 3, 4, 5]; const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue); console.log(sum); // Output: 15
In this example, the .reduce()
method is used to calculate the sum of all numbers in the numbers
array. The callback function takes the accumulator (initially set to the first element) and the current number, adding them together to update the accumulator. Since no initial value is provided, the first element of the array is used as the initial accumulator value.
The .reduce()
method can also be used for other operations, such as finding the maximum or minimum value, or transforming an array into a different data structure. The callback function can be customized to perform any operation and achieve the desired result.
- How to use sweetalert2
- How to Pass string parameter in an onclick function
- How to format number with commas and decimal in Javascript
- What does 'use strict;' means in Javascript
- How to detect if caps lock is pressed in Javascript
- How to create a Custom Event in Javascript
- How to Check if an Object Has a Property Properly in JavaScript
- How to convert an Uint8Array to string in Javascript