DEV Community

Discussion on: Demystifying Array.reduce(): How to understand it and when to use it in your code

Collapse
 
krofdrakula profile image
Klemen Slavič

I like to use reduce when transforming lists, like creating a Map from an array based on a key:

const userData = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }];

// a general-purpose array-to-map utility
const arrayToMap = (list, idMapper) =>
  list.reduce(
    (map, next) => {
      map.set(idMapper(next), next);
      return map;
    },
    new Map()
  );

console.log(arrayToMap(userData, user => user.id));