The reduce
method in JavaScript is used to perform a reduction operation on an array. It allows you to iterate over the elements of an array and accumulate a single value based on those elements. Here are a few use cases for the reduce
method:
JavaScript reduce example
Simple example code.
Summing or calculating the total: You can use reduce
to calculate the sum of all numbers in an array or the total of any other numerical values.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
});
console.log(sum); // Output: 15
Finding the maximum or minimum value: You can use reduce
to find the maximum or minimum value in an array.
const numbers = [5, 3, 9, 1, 7];
const max = numbers.reduce((accumulator, currentValue) => {
return Math.max(accumulator, currentValue);
});
console.log(max); // Output: 9
Concatenating strings: You can use reduce
to concatenate multiple strings in an array.
const fruits = ['apple', 'banana', 'cherry'];
const result = fruits.reduce((accumulator, currentValue) => {
return accumulator + ', ' + currentValue;
});
console.log(result); // Output: apple, banana, cherry
Counting occurrences: You can use reduce
to count the occurrences of specific values in an array.
const votes = ['yes', 'no', 'yes', 'yes', 'no', 'yes', 'no'];
const count = votes.reduce((accumulator, currentValue) => {
accumulator[currentValue] = (accumulator[currentValue] || 0) + 1;
return accumulator;
}, {});
console.log(count);
Output:
These are just a few examples of what you can achieve with the reduce
method in JavaScript. It provides a flexible way to transform and aggregate data in arrays based on custom logic, making it a powerful tool for array manipulation.
Comment if you have any doubts or suggestions on this Js Reduce topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version