DEV Community

Cover image for Using .reduce() in JavaScript
Stephen Nelson
Stephen Nelson

Posted on

Using .reduce() in JavaScript

Of all the native array methods provided by JavaScript, the native .reduce() method is arguably the strongest and most useful of the methods. The strength of the .reduce() function's versatility lies in its ability to return any type of value the developer wishes to return at the end of the code block. However, before that can happen the required parameters must be accounted for in order for the method to work properly. These required parameters for .reduce() are an array and a callback function, and while the seed parameter is listed in the syntax, it serves the purpose of a starting point for the callback function's accumulator parameter. Keep in mind as you read along that the examples provided in this blog are implemented on a basic level and more complex scenarios for .reduce() exist beyond this base line.

-Syntax:

let array.reduce(callback(accumulator, current), seed);
Enter fullscreen mode Exit fullscreen mode

-The array parameter in most cases outside of underscore.js is usually preceding the method itself as array.reduce(). This informs the interpreter that the developer is intending to reduce an array into a specific value. Now that the designated array is targeted for reduction, the developer still needs to declare a callback function to be called on the element of the current iteration of the loop. What is important to understand about the callback function is there are TWO required parameters and those are accumulator and current, and should be input in that same order. The accumulator is the total accumulated value that is updated after each iteration through the array and the current parameter is referring to the current element of the iteration.

-The last and perhaps the most versatile parameter that is passed into the .reduce() method is the seed parameter. The seed's flexibility stems from its ability to be any type of data from simple datatypes to complex datatypes. However, it is important to keep in mind that the seed acts as a starting point for the accumulator meaning if an array is being reduced to a single number and a sum is being returned as the result, it's crucial the for the seed to equal 0. If an array or object needs to be returned then the seed's input value at the time of the invocation should be either an empty array or object. The same should be exercised for strings as well.

Below are some examples of valid uses of the seed parameter:

let numbers = [1, 2, 3];

let sum = numbers.reduce(function(accumulator, current) {
    accumulator += current; 
    return accumulator
}, 0);

//returns the number value of 6
Enter fullscreen mode Exit fullscreen mode
  • The seed parameter of 0 allows the accumulator to begin at 0 accumulate a sum from all the elements in the numbers array. At the end of the code block the accumulator must be returned otherwise the value of the method will be considered undefined.
let words = ["This", "is", "a", "sentence"];

let sentence = words.reduce(function(accumulator, current) {
    accumulator += current + " ";
    return accumulator;
}, "");

//returns the string value of "This is a sentence"
Enter fullscreen mode Exit fullscreen mode
  • Note that now the seed was input as an empty string, the developer is now able to concatenate the strings in the words array into a single string.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8];

let allEvens = numbers.reduce(function(accumulator, current) {
    if (current % 2 === 0) {
        accumulator.push(current);
    }
    return accumulator;
}, []);

//returns a reduced array of even numbers [2, 4, 6, 8]
Enter fullscreen mode Exit fullscreen mode
  • This final example returns a reduced array from the provided numbers array array by testing if the current element is an even number. In order for this to work properly, an empty array must be provided as the seed so the accumulator's starting position is that empty array. Once the .reduce() method iterates through the numbers array, a condition will be tested on each current element (determining of the number is even) and if the current element passes that test then the element is pushed into the accumulator array.

  • In conclusion, the native .reduce() method is extremely useful when a specific copy of an array or object is needed, an accumulated sum to keep tabs on data occurrences, or a string needs to be formed from the elements of an array. These native array methods are tools provided to developers by JavaScript to be implemented and help strengthen the code, help with readability, and maintain dry code so repetition doesn't hinder functionality. For further information on the native .reduce() method, follow this link and dive further into the multitude of uses for .reduce().

Mozilla Developer

Top comments (0)