Hi there! In this blog, you will learn about the "reduce method" and how to use it in JavaScript. So, let's get started.
Reduce is one of the array methods in JavaScript. It takes an array as input and returns a single value. The reduce method is useful when you want to process every element of an array and update a common value based on the provided callback function.
Let's dive deeper:
Reduce takes two arguments:
- Callback function
- Starting point (initial value), let's call it "result" (*Optional)
It starts with the first element of the array, passes it to the callback function, and stores the result in "result". After processing the last element, it returns the final "result".
*Optional:
If the array is empty and no initial value is provided, reduce will throw a TypeError because there's no element to serve as the initial accumulator.
If the array has only one element and no initial value is provided, reduce returns that single element without invoking the callback.
Examples:
This examples will help you to understand how and where to use the reduce method. Feel free to ask questions in comments.
Easy:
Q. Given an array, sum its elements.
Solution using reduce method.
const arr = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumofArray = arr.reduce(
(result, element) => result + element,
initialValue,
);
console.log(sumofArray);
// Expected output: 10
Explanation:
Initially, the result will be zero, as we have provided zero as the second argument. Then, for each element, it will add that element to the result, and lastly, the final result value will be returned.
Medium:
This example is taken from: https://leetcode.com/problems/flatten-deeply-nested-array/description/
Q. Given a multi-dimensional array arr and a depth n, return a flattened version of that array.
A multi-dimensional array is a recursive data structure that contains integers or other multi-dimensional arrays.
A flattened array is a version of that array with some or all of the sub-arrays removed and replaced with the actual elements in that sub-array. This flattening operation should only be done if the current depth of nesting is less than n. The depth of the elements in the first array is considered to be 0.
Solution with Reduce method :
function flattenArray(arr, depth) {
if(depth===0) return arr;
return arr.reduce((result,element) => {
if(Array.isArray(element)&&depth>0) {
result.push(...flattenArray(element, depth-1));
} else {
result.push(element);
}
return result;
}, []);
}
Explanation:
If the depth is zero, we don't need to do anything. Otherwise, we use recursion and the spread operator to add the elements to the result.
That's it! I hope you've learned about the reduce method well.
References :
Array.prototype.reduce() from MDN
Top comments (5)
InitialValue
is actually optional. Your first example will run faster if you omit it. If it is not provided,reduce
will use the first value in the array as the initial value, then proceed from there.However, one minor gotcha here is that you'll get an error if the array is empty and you omit
initialValue
- so only do this if you know the array will have at least one item.Sure, I was just giving example how reduce can be used.
Thanks for giving feedback and adding more details.
One problem I find with reduce is people love to try and use it for everything once they know how to use it but it can very quickly become unreadable (even for the person that wrote it).
For the leetcode question, for instance, it's much nicer to use a flatmap.
That all being said reduce it a great tool to have in you arsenal for when it's needed. 😊