Javascript reduce method
Created By: chatGPT
The
reduce()
method in JavaScript is a powerful function that iterates through an array and executes a reducer function to reduce the array to a single value. It takes two parameters: a callback function and an optional initial value. The callback function itself takes four arguments: accumulator, current value, current index, and the source array.const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 15
In this example,
numbers.reduce()
calculates the sum of the values in the numbers
array. The accumulator starts at 0, and the method adds each currentValue to it as it iterates through the array. The result is stored in the sum variable.const product = numbers.reduce((accumulator, currentValue) => {
return accumulator * currentValue;
}, 1);
console.log(product); // Output: 120
The
reduce()
method can also be used for more complex operations, such as creating an object from an array. For instance, if you want to count the occurrence of each item in an array, you can do this:const fruits = ['apple', 'banana', 'orange', 'apple', 'orange', 'banana'];
const fruitCount = fruits.reduce((accumulator, currentValue) => {
accumulator[currentValue] = (accumulator[currentValue] || 0) + 1;
return accumulator;
}, {});
console.log(fruitCount); // Output: { apple: 2, banana: 2, orange: 2 }
In this example, the
fruitCount
object keeps track of how many times each fruit appears in the fruits
array. The accumulator starts as an empty object ({}), and for each currentValue, it increments the count.const words = ['hello', 'world', 'hello', 'reduce', 'method', 'world'];
const wordLengths = words.reduce((accumulator, word) => {
accumulator[word] = word.length;
return accumulator;
}, {});
console.log(wordLengths); // Output: { hello: 5, world: 5, reduce: 6, method: 6 }