AppDividend
Latest Code Tutorials

Definitive Guide to Understand Javascript Array reduce()

0

Javascript array reduce() is an inbuilt method that is used to apply a function to each element in the array to reduce the array to a single value. The reduce() function executes the provided function for each value of an array from left-to-right. The return value of a function is stored in an accumulator.

Understanding Javascript array reduce()

JavaScript array reduce() is one of the pioneer function of functional programming. The reduce() method accepts two parameters, the total and the current value. If you want to add all the values of an array, then use the array reduce() function.

It is similar to both Javascript map() and Javascript filter() but, it differs in the callback arguments.

The callback now receives an accumulator (it accumulates all the return values. Its value is the accumulation of a previously returned accumulations), a current value, a current index, and finally, the whole array. 

Syntax

The syntax of the reduce() function is the following.

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

# or

array.reduce(callback[, initialValue]);

Parameters

  1. function(total, currentValue, index, arr): It is a required parameter and used to run for each element of the array. It contains four-parameters which are listed below:
    1. total: It is the required parameter and used to specify an initialValue or the previously returned value of a function.
    2. currentValue: It is the needed parameter and used to determine the value of a current element.
    3. currentIndex: It is the optional parameter and used to specify an array index of the current element.
    4. arr: It is the optional parameter and used to determine an array object the current element belongs to.
  2. initialValue: It is the optional parameter and used to specify the value to be passed to the function as an initial value.

The syntax of Javascript reduce() is a slight different from the ones we have seen before.

In the other functions we have seen, the function we pass in generally needs only one argument representing each element of the array.

In the case of reduce() function, however, we need to pass two arguments. The first argument shows the value accumulated so far, and the second shows the current item. 

Return Value

Each time a function is called, its return value becomes the first argument for the next time it’s called. So if we have to find a sum of all the numbers in the array, we could use the javascript array reduce() function.

Note that we can also pass the third argument into Reduce. This value then becomes the starting value for our accumulator. So, it is also called the initial value.

By default, the starting value of an accumulator is the first element of the array we pass in.

Application

Let’s say that we have an array representing our shopping list, and we want to find the total cost of all the elements in it in this scenario, we can use the js array reduce function.

Let us take a simple example of the reduce() function and see how this works.

// server.js

const data = [5, 10, 15, 20, 25];

const res = data.reduce((total,currentValue) => {
  return total + currentValue;
});

console.log(res); // 75
  1. In this example, the reduce() method accepts two parameters, the total and the current value.
  2. The reduce() function cycles through each value in the array much like it would in the for-loop.
  3. In this specific example, we want to add a current value to the total values.
  4. The calculation is continuously repeated for each value in an array, but each time a current value changes to the next value in the array, moving right.
  5. When there are no more values left in the array, reduce() method returns the total value.

How reduce() works in Javascript.

See the following code.

data = [2, 4, 6, 8, 10]

const reducer = (accumulator, currentValue, currentIndex, array) => accumulator + currentValue

result = data.reduce(reducer)

console.log(result)

Okay, so our function reducer() takes four parameters.

Now, let’s see a descriptive table that shows what is happening on each iteration.

callback iterationaccumulatorcurrentValuecurrentIndexarrayreturn value
first call241[2, 4, 6, 8, 10]6
second call662[2, 4, 6, 8, 10]12
third call1283[2, 4, 6, 8, 10]20
fourth call20104[2, 4, 6, 8, 10]30

 

The value returned by the reduce() would be that of the last callback invocation 30.

Passing no initial value to the reduce() Function

If you don’t pass the initial value, the reducer will assume the first item in your array as your initial value.  This worked fine in some examples because we were adding up the list of numbers.

data = [11, 21, 19, 18, 46]

const reducer = (accumulator, currentValue) => accumulator + currentValue

result = data.reduce(reducer)

console.log(result)

Output

115

In this example, you can see that we have not passed the initial value in the reduce() function. It takes the first element as an initial value and starts reducing and will add all the elements and returns a single value as an output.

Passing an initial value to the reduce() function

If we pass the initial value as an argument, then it will position itself as the first value, and then it will start reducing it.

data = [11, 21, 19, 18, 46]

const reducer = (accumulator, currentValue) => accumulator + currentValue

result = data.reduce(reducer, 29)

console.log(result)

Output

144

In this example, you can see that we have passed the initial value as 29 to the reduce() function. That means it takes 29 as an initial value and starts reducing and will add all the elements, including 29, and returns a single value as an output. If you see in the output, then you can verify that it has added the 29 values in the final output.

The reducer function’s returned value is assigned to the accumulator, whose value is retained across each iteration throughout the array, and conclusively becomes the final, single resulting value.

TypeError: Reduce of the empty array with no initial value

If an array is empty and no initial value is provided, TypeError will be thrown.

data = []

const reducer = (accumulator, currentValue) => accumulator + currentValue

result = data.reduce(reducer)

console.log(result)

Output

result = data.reduce(reducer)
              ^

TypeError: Reduce of empty array with no initial value
    at Array.reduce (<anonymous>)
    at Object.<anonymous> (/Users/krunal/Desktop/code/pyt/app.js:5:15)
    at Module._compile (internal/modules/cjs/loader.js:1128:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10)
    at Module.load (internal/modules/cjs/loader.js:983:32)
    at Function.Module._load (internal/modules/cjs/loader.js:891:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47

If the array only has one item (regardless of position) and no initial value is provided, or if the initial value is provided, but the array is empty, the solo value will be returned without calling the callback.

data = []

const reducer = (accumulator, currentValue) => accumulator + currentValue

result = data.reduce(reducer, 11)

console.log(result)

Output

11

 Flattening arrays using Javascript reduce method

We can use the reduce() function to flatten the nested amounts into a single array.

We set an initial value to the empty array and then concatenate the current value to the total.

// server.js

const data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

const flatValues = data.reduce((total, value) => {
  return total.concat(value);
}, []);

console.log(flatValues);

Javascript Reduce Example Tutorial

You must return something for a reduce function to work.

Always double-check and make sure that you’re returning the value you want.

When your reducer function is called, its return value becomes the new previousValue argument for next time the reducer function is called. That’s the magic.

After the reducer function is called and given the very last object in the array, its return value will be a return value of reduce() function.

ES6 Syntax of Javascript reduce() function

See the following code.

// app.js

const pounds = [11.21, 19.21, 46.21];

const sum = pounds.reduce((total, amount) => total + amount); 

console.log(sum);

See the output.

➜  es git:(master) ✗ node app
76.63
➜  es git:(master) ✗
  1. In this example, Reduce accepts the two parameters, the total and the current amount.
  2. The reduce() method iterates over each number in the array, much like it would in the for loop.
  3. When the loop starts, the total value is the number on the far left (11.21), and the current amount is the one next to it, which is (19.21).
  4. In this specific example, we want to add the current amount to the total.
  5. The calculation is repeated for each item in the array, but each time the current value changes to a next number in the array, moving right.
  6. When there are no more numbers left in an array, the method returns a total value.

Find average using reduce() Method in Javascript.

In the above example, instead of logging the sum, what you could do is to divide the sum by a length of the array before you return the final value.

The way to do this is by taking leverage of the other arguments in the reduce() function.

The first of those arguments is the index. Much like the for loop, the index refers to the number of times the reducer has looped through the array.

The last argument is the array itself.

See the following code example.

// app.js

const pounds = [11, 21, 16];

const avg = pounds.reduce((total, amount, index, array) => {
  total += amount;
  if (index === array.length - 1) {
    return total / array.length;
  } else {
    return total;
  }
});

console.log(avg);

See the output.

➜  es git:(master) ✗ node app
16
➜  es git:(master) ✗

Finding repeated items in an array

Let’s say you have the collection of items, and you want to know how many of each item is in the collection.

In this scenario, the Javascript reduce method can help us.

// app.js

const pounds = [11, 21, 16, 19, 46, 29, 46, 19, 21];

const count = pounds.reduce( (data, pound) => {
  data[pound] = (data[pound] || 0) + 1 ;
  return data;
} , {})

console.log(count);

See the output.

➜  es git:(master) ✗ node app
{ '11': 1, '16': 1, '19': 2, '21': 2, '29': 1, '46': 2 }
➜  es git:(master) ✗

To tally several items in an array, our initial value must be an empty object, not an empty array.

Since we are going to be returning the object, we can now store key-value pairs in the total.

On our first pass, we need the name of the first key to be our current value, and we want to give it the value of 1.

This gives us the object with all the numbers as keys, each with a value of 1.

We want an amount of each number to increase if they repeat.

To do this, on the second loop, we check if the total contains the key with a current number of the reducer.

If it doesn’t, then we create it. If it does, then we increment the value by one.

Removing duplicate items in an array

Array.reduce() is a useful function when we have to remove the duplicate items in the array. We can use an array.push() and array.indexOf() functions with array.reduce() function to remove duplicate items from the array.

let data = [1, 2, 3, 1, 4, 3, 3, 5, 5, 5, 8, 9]
let myOrderedArray = data.reduce(function (accumulator, currentValue) {
  if (accumulator.indexOf(currentValue) === -1) {
    accumulator.push(currentValue)
  }
  return accumulator
}, [])

console.log(myOrderedArray)

Output

[
  1, 2, 3, 4,
  5, 8, 9
]

Grouping objects by a property

We can group objects by its property using the array.reduce() method.

let student = [
  { name: 'Rick', enrollment: 60 },
  { name: 'Beth', enrollment: 40 },
  { name: 'Jerry', enrollment: 40 }
];

function groupBy(objectArray, property) {
  return objectArray.reduce(function (accumulator, obj) {
    let key = obj[property]
    if (!accumulator[key]) {
      accumulator[key] = []
    }
    accumulator[key].push(obj)
    return accumulator
  }, {})
}

let groupedStudent = groupBy(student, 'enrollment')
console.log(groupedStudent)

Output

{
  '40': [
    { name: 'Beth', enrollment: 40 },
    { name: 'Jerry', enrollment: 40 }
  ],
  '60': [ { name: 'Rick', enrollment: 60 } ]
}

In this example, we have grouped object using ‘enrollment’ propertyIn the output, you can see that 40 enrollment has two objects, and 60 has one object. The returned object has grouped property, and value is the object according to that property.

Conclusion

Javascript reduce takes an array, and based on the function we give it, reduces the array down to a single value. For example, it might take an array of numbers and reduce it down to a sum or an average. If you don’t pass the initial value, the reduce() function will assume the first item in your array as your initial value.

Another most common mistake is to forget to return the total. You must return something for a reduce function to work. Always double-check and make sure that you’re returning a value you want.

Finally, the Javascript array reduce() function example is over.

Recommended Posts

Javascript Array lastIndexOf()

Javascript Array includes()

Javascript Array keys()

Javascript Array findIndex()

Javascript Array indexOf()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.