Mauro Bringolf

Currently geeking out as WordPress developer at WebKinder and student of computer science at ETH.

Array.prototype.reduce in action: Remap an array to id indexed object

December 21, 2017

The functions reduce, map and filter have been one of the great discoveries in programming for me this year, especially in JavaScript. The first few use cases took some effort to implement but soon they became my default way of thinking about list transformations. I even went a bit further and explored how reduce can implement the others earlier this year1. And recently I encountered a stellar use case for reduce that I would like to share. Imagine the following situation:

This is a problem I encountered many times when starting to program. The straight-forward solution of searching the array for each of the given id‘s is not efficient, because in the worst case you will look at all objects during every query. An array is clearly the wrong data structure to work with here. What we need is an object with the id‘s as keys and objects as values. If you are generating the data yourself, then you are probably better of changing the structure to an object instead of an array. In my case that was not possible, because the array came in as a result of an API. So I decided to build an additional object that maps keys to objects. This abstract operation is exactly a reduce operation. Here is how it looks:

// Creates a key-mapping from a list
const elementsByKey = elements.reduce(function(acc, el) {
  acc[] = el;
  return acc;
}, {});

// Direct element access via key

The reduce call traverses the whole array once, but then we can directly reference any element by its id instead of having to search again. And since JavaScript works with objects by reference, the constructed object elementsByKey only contains references and not copies of the objects. It is really just the light mapping into the array we need.

Let me know if you have alternative solutions!