๐Ÿฟ 5 min. read

Understanding Reduce in JavaScript

Monica Powell

Reducing an array is a helpful functional programming technique to use when you need to reduce multiple values into a single value. Although that single value isn't limited to being an integer it can be an array, an object...etc. I've found reduce to be a handy method to have at your disposal during technical interviews. This article will introduce ES6's reduce() method and then walk through various ways to use reduce and discuss other built-in methods that abstract reduce() like map() and filter().

The general structure when using reduce() is:

1input.reduce(callback, initialAccValue)
2// Note: the `initialAccValue` is optional but effects how reduce() behaves

When an initialAccValue is supplied,the callback function is called on every item within the input array. The callback function will then mutate the accumulator until it has gone through every item and it reaches it final value. Thet final value of the accumulator is ultimately the return value of reduce().

1input.reduce((accumulator, item) => {
2 // What operation(s) should occur for each item?
3 // What will the accumulator value look like after this operation?
4 // ๐Ÿšจ: the accumulator value needs to be explicitly returned.
5}, initialValue)

The reducer function can take up to four arguments and look like

1arr.reduce(callback(accumulator, currentValue[, index[, array]] )[, initialValue])

illustrated example of using filter vs reduce to filter fruits out of a collection of food

You can read more about reduce() and the index and array parameters at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce.

Reducing an array to a single number

A common way reduce() can be used is to return the sum of all of the values in an array.

In the below code each item in the values array is added to the accumulator in the callback function. The initial value of the accumulator is explicitly set to 0. During each iteration through the values in input the accumulator grows larger since each time the callback function is called it is passed in the resulting accumulator value from the previous iteration.

1const input = [1, 100, 1000, 10000]
2const sum = input.reduce((accumulator, item) => {
3 return accumulator + item
4}, 0) // 11101

If we walk through each iteration of the above reduce method it will look something like this:

  1. accumulator = 0, item = 1

    • the returned accumulator = 1 + 0 = 1
  2. accumulator = 1, item = 100

    • the returned accumulator = 1 + 100 = 101
  3. accumulator = 101, item = 1000

    • the returned accumulator = 101 + 1000 = 1101
  4. accumulator = 1101, item = 10000

    • the final (and only number) returned from the reduce function is 11101. This number is reached because 1101 + 10000 = 11101 and 10000 is the last item in the input array.

Mapping Items with map() and reduce()

If you want to return a new array that is the result of performing an operation on each item in an array then you can use map() or reduce(). map() allows you to more concisely accomplish this than reduce() but either could be used. The example below shows how to return an array that contains squared versions of numbers in an original array using both map() and reduce().

Using map()

1const numbers = [1, 10, 100]
2const squared = numbers.map(item => Math.pow(item, 2))
3// [1, 100, 10000]

Using reduce()

1const numbers = [1, 10, 100]
2const squared = numbers.reduce((acc, number) => {
3 acc.push(Math.pow(number, 2))
4 return acc
5}, []) // [1, 100, 10000]

Filtering Items with filter() and reduce()

If you ever need to filter out values in an array to only retain values that meet certain criteria you can use either filter() or construct a new array that only is compromised of items that pass the criteria. Below are examples of using filter() and reduce() to only return the even numbers from an array of digits.

Using filter()

1const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2const evenNumbers = numbers.filter(number => number % 2 === 0)
3// [2, 4, 6, 8, 10]

Using reduce()

1const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2const evenNumbers = numbers.reduce((acc, number) => {
3 if (number % 2 == 0) {
4 acc.push(number)
5 }
6 return acc
7}, [])
8// [2, 4, 6, 8, 10]

Reducing an array to a single object

Although reduce() has to return a single value but that single value doesn't have to be an integer or array it can also be an object. The following example will walk through how to reduce an array into a single object. This prompt was taken from VSchool's reduce practice exercises.

The prompt was:

Given an array of potential voters, return an object representing the results of the vote. Include how many of the potential voters were in the ages 18-25, how many from 26-35, how many from 36-55, and how many of each of those age ranges actually voted. The resulting object containing this data should have 6 properties.

The input of voters looked like:

1const voters = [
2 { name: "Bob", age: 30, voted: true },
3 { name: "Jake", age: 32, voted: true },
4 { name: "Kate", age: 25, voted: false },
5 { name: "Sam", age: 20, voted: false },
6 { name: "Phil", age: 21, voted: true },
7 { name: "Ed", age: 55, voted: true },
8 { name: "Tami", age: 54, voted: true },
9 { name: "Mary", age: 31, voted: false },
10 { name: "Becky", age: 43, voted: false },
11 { name: "Joey", age: 41, voted: true },
12 { name: "Jeff", age: 30, voted: true },
13 { name: "Zack", age: 19, voted: false },
14]

I ended up writing the voterResults function below which takes in an array that is shaped like the voters array above. I decided to set the initial accumulator value to:

1const initialVotes = {
2 youngVotes: 0,
3 youth: 0,
4 midVotes: 0,
5 mids: 0,
6 oldVotes: 0,
7 olds: 0,
8}

The initialVotes object was the same shape as the final value I needed the reduce() to return and encapsulated all of the potential keys that would be added and defaulted each to 0. This structure easily captures categories that ended up having a total of 0 at the end and also eliminated the need to have check that the current value of a key existed before incrementing it.

Within the callback function logic needed to be implemented to determine which peer group someone was in based on conditional logic related to their age. That peer data was also used to increment the voting data for their peer group if they voted.

1function voterResults(arr) {
2 const initialVotes = {
3 youngVotes: 0,
4 youth: 0,
5 midVotes: 0,
6 mids: 0,
7 oldVotes: 0,
8 olds: 0,
9 }
10
11 const peersToVotePeers = {
12 youth: "youngVotes",
13 mids: "midVotes",
14 olds: "oldVotes",
15 }
16
17 return arr.reduce((acc, voter) => {
18 if(voter.age < 26)
19 peers = "youth"
20 } else if (voter.age < 36) {
21 peers = "mids"
22 } else {
23 peers = "olds"
24 }
25 if (!voter.voted) {
26 // if they didn't vote let's just increment their peers
27 // for example for { name: "Zack", age: 19, voted: false }
28 // The peer group would be "youth" and we'd increment acc["youth"] by one
29 return { ...acc, [peers]: acc[peers] + 1 }
30 } else {
31 const votePeers = peersToVotePeers[peers];
32 // for example for { name: "Jeff", age: 30, voted: true }
33 // The peer group would is "mids"
34 // acc["mids"] and acc["midVotes"] are both incremented by one
35 return {
36 ...acc,
37 [peers]: acc[peers] + 1,
38 [votePeers]: acc[votePeers] + 1,
39 }
40 }
41 }, initialVotes)
42}

The object output from voterResults(voters) is:

1{ youngVotes: 1,
2 youth: 4,
3 midVotes: 3,
4 mids: 4,
5 oldVotes: 3,
6 olds: 4
7}

Notes

  • Often accumulator is abbreviated as acc.
  • The callback function must explicitly return a value or else reduce() will return undefined.

This article was published on March 29, 2020.


Don't be a stranger! ๐Ÿ‘‹๐Ÿพ

Thanks for reading "Understanding Reduce in JavaScript". Join my mailing list to be the first to receive my newest web development content, my thoughts on the web and learn about exclusive opportunities.

    ย 

    I wonโ€™t send you spam. Unsubscribe at any time.

    Webmentions

    6932
    • that_developer ๐Ÿ‘จ๐Ÿพโ€๐Ÿ’ป
    • Alice Chang
    • Urmil Bhatt
    • Alexandru Frangeti
    • Jesรบs Macedo ๐Ÿค˜๐Ÿป
    • ๐—”lex
    • Haja C.
    • Nnadozie Ezeani
    • Women Who Code Lagos
    • I zetta
    • Dunnex
    • #Genjutsuโœจ๐Ÿ‘จโ€๐Ÿ’ป
    • Raghavan Iyengar
    • Ajay
    • BRT_GAMES
    • Manasse Gitau
    • Tia Esguerra
    • Samuel Kitavi
    • Jane Tracy
    • Luis Pesaressi
    • Tony Hernandez
    • Fabian Brash
    • iloveducks2
    • Ishโˆ†n ๐Ÿ›ธ
    • Amos Aidoo
    • NOC ๐Ÿฆ‰
    • Emma Milner
    • Sergey Chernyshev
    • Hannah Goodridge
    • Ashes
    • daddynefs โ˜„๐Ÿš€
    • Vinod Kumar
    • ghostCod3r
    • maxosen74
    • M
    • Juan Camilo Rico
    • Linda T.
    • Roz
    • Ruby Jane ๐Ÿ‡ต๐Ÿ‡ญ
    • pavt
    • +229