Convert an array of objects with a unique id property to a Map

ecmascript-6, es6-map, javascript

Solution

You want to reduce your array into a map:

const arr = [{id:1},{id:2},{id:2}];

const map = arr.reduce((acc, item) => acc.set(item.id, item), new Map());

console.log(map.get(1));

Here is a JSPref against using `map` and `forEach`.

In Chrome v53 `reduce` is fastest, then `forEach` with `map` being the slowest.

Problem

I have an array of objects, where each object has a unique member called `id`. How do I create a Map where the `id` if the Map's key?

Original source