dataquarium

Little Bits: JavaScript's Array reduce()

December 10, 2017

Here’s a quick intro to a bit of code that I love: JavaScript’s Array reduce(). reduce is a function that takes an array of items in JavaScript and transforms it into a single item. A user-defined function is provided that dictates how the final value is calculated as the reduce function goes through each item in the array. For example, you can write a simple sum function with a reducer by keeping a running total of the values in the array like so:

[1, 2, 3, 4, 5].reduce((acc, curr) => acc + curr);
// -> 15

An animation of the reducer in action

An animation of the reducer in action

The reduce function can be used for all kinds of operations, including chaining together sequential async calls based on an array. To learn more, check out the video below:

fpjavascript