DEV Community

Cover image for The Power of Reduce
Sean Niehus
Sean Niehus

Posted on • Updated on

The Power of Reduce

Reduce is powerful Javascript method that is crucial for every beginning programmer to become familiar with . In a nutshell, reduce will iterate through an array and return a single value. That single value can be of any data-type, be it primitive or complex. As reduce loops through the input collection, it invokes a callback function on every value, updating the return value at every pass. The value returned can be a string, number, array or an object. Reduce is an invaluable tool that can be used in and endless amount of ways, I show a few simple examples of how it can be used. First, an example using it to return a simple data type, number, here the sum of all elements in numbers:

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var reduced = function(array){
  return array.reduce(function(accumulator, element){
return accumulator += index; 
}); 
};
reduced(numbers);  //returns 55
Enter fullscreen mode Exit fullscreen mode

Above the callback function invokes the function on every element of the numbers array and updates the value of the accumulator and returns the final value when the iteration is complete. Above, the return value is the same type of data as each element in the collection, but reduce can return complex data as well. Say, you have an array of users and want to return an array of only the user's objects of those that are younger than 30:

var users = [{name:'john', age: 27, accountNumber: 383838}, 
             {name: 'jane', age: 26, accountNumber: 388728}, 
             {name: 'bob', age: 33, accountNumber: 399384}];

var reducedArray = function(array){
  return array.reduce(function(accumulator, object){
    if(object.age < 30){
      accumulator.push(object);
    }
    return accumulator;
  }, [])
};
(reducedArray(users)); 




Enter fullscreen mode Exit fullscreen mode

Above, the function works the same way, iterates through and updates the return value at every call and returns a simplified array with only 2 objects. The callback function here takes in one more argument (after the body of the function), the empty array is initial value of the accumulator, called the seed. This is optional (recall the first example did not have one), if one is not supplied the first element of the input array becomes the initial value of the accumulator and the iteration will start at index 1.

Taking a look at the function created from scratch, gives us a view of what is happening in the background whenever it is used:

function reduceFromScratch(array, iterator, seed){
  let accumulator = seed;
  let i = 0;

  if(accumulator === undefined){
    accumulator = array[0];
    i = 1;
  }
    for(; i < array.length; i++){
      let elem = array[i];
      accumulator = iterator(accumulator, elem, array, seed);  
      }
      return accumulator;
}
Enter fullscreen mode Exit fullscreen mode

First, the function checks to see if a starting value has been passed in, assigns it to the accumulator if it has. If the seed hasn't been provided it makes the first element the starting value and tells the loop to begin at the second element instead of the first. It then invokes the iterator function on every element and updates the accumulator per directions of the callback.

There are few basic array methods in javascript that get used repeatedly when working with large collections of nested data such as JSON files. The map and filter methods are invaluable and can be chain together to extract precise slivers of data from collections, but often reduce can be used alone to achieve the same results with less code.

Take a look again at the second example above that returned the objects that were for users who are under 30. If just the account numbers were need, filter and map could handle the job, but reduce can do it on it's own:

var users = [{ name:'john', age: 27, accountNumber: 383838}, 
             {name: 'jane', age: 26, accountNumber: 388728}, 
             {name: 'bob', age: 33, accountNumber: 399384}];

var reducedArray = function(array){
  return array.reduce(function(accumulator, object){
    if(object.age < 30){
      accumulator.push(object.accountNumber);
    }
    return accumulator;
  }, [])
};
console.log(reducedArray(users));

Enter fullscreen mode Exit fullscreen mode

This basic example shows reduces versatility, but there is no limit to the possibilities of what reduce can accomplish. It's not hard to imagine how a retail company could use reduce on its user's database to precisely target customers based on their data. Say, if you need to send an email to everyone who purchased a certain product. Reduce will return their addresses if the product is on their purchases array. It can return something as simple a number representing an average balance or as complex as nested objects, the possibility are endless.

In conclusion, these very simple examples are only the a tiny sample of reduce is capable of. Knowing how to use reduce is a great asset and can make code much more efficient and concise, making it easier to debug and reduce repitition, something all of us should strive for.

Top comments (0)