Knowledge · Professional Development

Clean Aggregation with JavaScript ‘Reduce’

A common beginner (?) programming question is as follows:

Given an array of items, find how many instances of each item occurs in the array.

For example, given the below array of US states, return an object with the count of number of instances of each state:

const data = ["CO", "FL", "CO", "CA", "NY", "NY", "WY", "NY", "MI"];

The interesting thing about this problem is it is not known which states are going to be present in the array, so the answer must be flexible. There’s an elegant way to solve the problem using JavaScript’s reduce array method.

Reduce takes a callback function that operates on an accumulator. In this case, the accumulator is the count of instances each state appears, represented by obj[item] in the below. You also need to specify a default value, which will be an empty object {}. In our case, the solution is looks like this:

let states = data.reduce((obj, item) => {
  obj[item] ? obj[item]++ : obj[item]=1; 
  return obj;
},{});

Given the data array, we start with the empty object and for each item in the array if there is a key in the object with the value of item (which will be “CO”, “FL”, etc.), we increment the count by one. If there is no key in the object with the value of the item, obj[item] will be falsy, and we set the obj[item] value to 1, initializing it. The next time the item is found in the array, obj[item] will be incremented. Then we return the object obj. The result will look like this:

{ CA: 1, CO: 2, FL: 1, MI: 1, NY: 3, WY: 1 }

See a working example here.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s