DEV Community

Linas Spukas
Linas Spukas

Posted on

Array Transformations With `reduce()` Method

JavaScript Array has an excellent method reduce() that can do amazing transformations with arrays, like flatten it or transform to other data types.
This method runs and executes a provided function on every value of the array and outputs a single value.
In this article, I'd like to share a few examples of how to use it in different cases.

Method Structure

The method takes a callback and initial value. The callback takes four arguments:

  • accumulator - accumulates return value
  • value - current value that is processed
  • index - index of the current element (optional)
  • array - source array (optional)
Array.prototype.reduce(function(acc, value, ?index, ?array), ?initialValue)

The initial value is optional. If it not provided, the callback will take the first array element and use it as the initial value. If the initial value supplied, the following array elements will run against it, accumulate new results, and you have to make sure you will return it from the function.

Also, I need to mention that running a reducer on an empty array will result in throwing an error. Always check and make sure that the array has at least one element.

Use Cases

Below you'll find three examples, how you can reduce and transform arrays for your benefit.

Return a Sum of Values

If you have an array of numbers, it is straightforward to get a sum of them.

[1, 2, 3].reduce((acc, value) => acc + value); // output 6

We don't need to specify an initial value. The reducer function will take the first element 1 and use it as a start value to accumulate and return a new result. With arrow function, you don't need to specify a return statement. The new result will be returned by default.

Return a Count of Instances

Group values into and object to know how many times a value gets repeated in an array:

['a', 'b', 'a', 'c', 'b'].reduce((acc, value) =>
  acc[value]
  ? { ...acc, [value]: acc[value]++ }
  : { ...acc, [value]: 1 },
{})
// output { a: 2, b: 2, c: 1 }

Here we specified the initial value as object and on each iteration of arrays element doing a check if the value exists in the object. If it does, we return the object with the previous values (...acc) and an incremented value [val]: acc[val]++.

Flatten Arrays

If you have an array of arrays, you can easily flatten the values and reduce to one array of values with a litle help of spreading:

[['a', 'b'], ['c'], ['d', 'e']].reduce((acc, value) => [...acc, ...value], []);
// output [ "a", "b", "c", "d", "e" ]

Sum Up

reduce() method is compelling and flexible, can combine different array methods, like map() and filter(). Perform mathematical operation or run asynchronous code in the sequence. And because it is flexible, there is more space for mistakes. When combining a few methods and processes into one, it is hard to understand the intention and debug it.

Top comments (1)

Collapse
 
davidyaonz profile image
David Yao

hi, just for the reference, the correct code for reducing count of instances is :
['a', 'b', 'a', 'c', 'b'].reduce((acc, value) =>
acc[value]
? { ...acc, [value]: acc[value]+1 }
: { ...acc, [value]: 1 },
{});

Cheers