Array.reduce()

The array reduce() method handles situations where you have an array of items, and you want to process each item of the array in turn to end up with a single item or value.

The items in the array can be anything, an integer, a string, an object. The single end result can also be anything too, as long as it can be generated by processing each item in an array sequentially until all have been processed.

The method signature of reduce:

ARRAY.reduce(REDUCE_METHOD, INITIAL_VALUE)

Where:

  • ARRAY is the array to be reduced, one item at a time
  • REDUCE_METHOD is the method that reduces the array one step at a time.
  • INITIAL_VALUE is the starting value for the accumulator.

The reduce method is given the following parameters, in order:

  • The accumulator, the item that gets updated when processing each element in turn
  • The current item in the array. Your method takes this item and uses it to update the accumulator.

A few concrete scenarios:

  • Sum a list of integers:

      var sum = integers.reduce(
          (total, value) => total += value
      )
    
  • Return a range that covers the list of integers:

      var range = integers.reduce(
          (range, value) => {
              if (value < range.start || range.start === false) {
                  range.start = value;
              }
              if (value > range.end || range.end === false) {
                  range.end = value;
              }
              return range;
          },
          {start: false, end: false}
      );
    

    Or as a pure expressional function:

          var range = integers.reduce(
              (range, value) => { {
                  start: ( range.start === false || value < range.start ) ? value : range.start,
                  end: ( range.end === false || value > range.end ) ? value : range.end
              } },
              {start: false, end: false}
          )
    
  • Given a list of words, calculate the frequency of each word

      var wordFrequency = words.reduce(
          (frequency, word) => {
              if (frequency[word]) {
                  frequency[word]++;
              } else {
                  frequence[word] = 1;
              }
              return frequency;
          },
          {}
      )
    
  • Finding the oldest published timestamp in an array of articles:

      var oldest = articles.reduce(
          (oldest, article) => (
              (article.timestamp < oldest || !oldest)
                  ? article.timestamp
                  : oldest
          ),
          0
      );
    
  • Build up an object from an array of key-value strings:

      var headers = lines.reduce(
          (headers, line) => parseHeaderLine(line, headers),
          {}
      )
    
  • Creating a lookup table keyed off an object property

      var userLookup = users.reduce((userMap, user) =>
          {
              userMap[user.email] = user;
              return userMap;
          },
          {}
      );