In this article, we are going to learn about one of the most powerful methods available in javascript that can be used to perform different actions like:
Segregation
Aggregation
Execution in series
Array.reduce accepts two parameters one is callback function and the other one is initialValue. Where initialValue is an optional.
Array.reduce(callback,initialValue);
This callback
function has 4 parameters (previousValue, currentValue, currentIndex, array)
previousValue - Value returned from the last call of same function
currentIValue - current value of the array
currentIndex - current index of the array
array - array itself.
Now let see how can we perform different operations with Array.reduce
Segregation
Let's see an example of segregation first. Here we are going to segregate all the even and odd numbers into arrays from an array of numbers.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const segregated = numbers.reduce((result, number) => {
if (number % 2 === 0) {
result.even.push(number);
} else {
result.odd.push(number);
}
return result;
}, { even: [], odd: [] });
console.log(segregated.even); // Array of even numbers: [2, 4, 6, 8]
console.log(segregated.odd); // Array of odd numbers: [1, 3, 5, 7, 9]
Aggregation
Here we have an example for aggregation as well. Here reduce method iterates through the numbers array and for each element, it adds the element to the accumulator. Here 0 is provided as the initialValue
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 15
Execution in series
Now let's see one more example where we will see how to execute function in sequence. The result of 1st function from the array of functions will be passed as the argument of 2nd function and then the final result will return.
// functions
const upperCase = (str) => {
return str.toUpperCase();
};
const reverse = (str) => {
return str.split('').reverse().join('');
};
const append = (str) => {
return "Hello " + str;
};
// array of functions to be piped
const arr = [upperCase, reverse, append];
// initial value
const initialValue = "hashnode";
const finalValue = arr.reduce((previousValue, currentElement) => {
// pass the value through each function
// currentElement is the function from the array
const newValue = currentElement(previousValue);
// return the value received from the function
return newValue;
}, initialValue);
console.log(finalValue);
// Hello EDONHSAH
We can also execute array of asynchronous function in sequence using reduce. Here let's see an example we will simulate asynchronous function with setTimeout
// An array of asynchronous functions that resolve after a delay
const asyncFunctions = [
() => new Promise((resolve) => setTimeout(() => resolve(2), 1000)),
() => new Promise((resolve) => setTimeout(() => resolve(3), 1000)),
() => new Promise((resolve) => setTimeout(() => resolve(5), 1000)),
];
// Initial value
const initialValue = Promise.resolve(1);
asyncFunctions.reduce((previousPromise, currentFunction) => {
return previousPromise.then((result) => {
return currentFunction().then((value) => {
console.log(`Current value: ${value}, Previous result: ${result}`);
return value + result;
});
});
}, initialValue)
.then((finalResult) => {
console.log(`Final result: ${finalResult}`);
});