How to Reduce Javascript Arrays With array.reduce()

Oftentimes, we find ourselves needing to reduce an array down to one of the many Javascript primitive types like a number, string, boolean, object, another array (we’ll see some examples of this later), or even a custom type defined in our project. Javascript reduce() is an inbuilt array method that executes a callback function known as a reducer on each element of the array and results in a single output value. The reduce() method executes the function for each value of the array (non-empty array) from left to right.

The reduce() method has the following syntax:
let arr = [];arr.reduce(callback(acc, curVal, index, src), initVal);
Parameters:
- Accumulator (acc)
- Current Value (curVal)
- Current Index (index)
- Source Array (src)
- Initial Value (initVal)
Accumulator | required: This is the accumulated value previously returned from the function or the initial value if it was supplied.
Current Value | required: This is the value of the current element in the array.
Current Index | optional: This is the index of the current element in the array.
Source Array | optional: This is the array object reduce() was called upon.
Initial Value | optional: This is the initial value to be passed to the function. If no initial value is supplied, the first element in the array will be used as the initial accumulator value and the second element becomes the current value
Note: If the array only has one element and no initial value is provided, or an initial value is provided but the array is empty, the single will be returned without calling the callback. Calling reduce() on an empty array without an initial value will throw a TypeError.
Working Examples
- Let’s try reducing an array of arrays to a one-dimensional array
In this example, the initial value is set to an empty array, which is the same as the initial accumulator value.
2. Guess what? This works on an array of objects too! The method runs the callback on the array elements irrespective of their type.
This example reduces an array of objects into a single string, matching the item to the quantity
Conclusion
While the reduce() method may appear confusing at first glance, the logic is simple: reduce an array to a single value by iterating through the array using a callback function.
Further Reading
To gain more knowledge on the various ways the reduce() method can be used, check out Reduce Method In Javascript or MDN web doc
Feel free to leave your comments and suggestions. Let’s keep the conversation going! You can also check out my other article on array flattening