Using Array reduce

Publikováno: 14.5.2019

Every developer who specializes in any programming language will tell you there’s a powerful tool the language provides that they rarely use and wish they knew more about. For me, it’s Array.prototype.reduce. I quite enjoy the other Array methods like map, filter, and find, but reduce is one that I knew was powerful but never […]

The post Using Array reduce appeared first on David Walsh Blog.

Celý článek

Every developer who specializes in any programming language will tell you there’s a powerful tool the language provides that they rarely use and wish they knew more about. For me, it’s Array.prototype.reduce. I quite enjoy the other Array methods like map, filter, and find, but reduce is one that I knew was powerful but never really had much use for.

It wasn’t until I was refactoring some of the Firefox DevTools Debugger code that I found a great use case for reduce — one I plan on using in the future.

Methods like forEach and map were created to avoid side effects, and reduce is no exception. In this case, however, reduce can return an Object other than an Array. Take this case for example:

// Samples sources
const sources = [
  {
    id: "server1.conn13.child1/39",
    url: "https://davidwalsh.name/"
  },
  {
    id: "server1.conn13.child1/37",
    url: "https://davidwalsh.name/util.js"
  }
];

// Return an object of sources with the keys being "id"
const sourcesMap = sources.reduce((map, source) => {
  map[source.id] = source
  return map;
}, {});

In the example above, we take an array of Source objects and return a single object literal with each Source‘s id as the key:

{
  "server1.conn13.child1/39": {
    "id": "server1.conn13.child1/39",
    "url": "https://davidwalsh.name/"
  },
  "server1.conn13.child1/37": {
    "id": "server1.conn13.child1/37",
    "url": "https://davidwalsh.name/util.js"
  }
}

Note that the {}, which is the last argument to reduce, is starting/default object to be returned. If there were no items in the array, {} would be returned. Also appreciate that an array method returns an object literal and not a modified array!

It’s crazy that I’ve not used reduce more, but that’s just life in our industry — we all have a few APIs we just haven’t used much of. What feature of JavaScript have you frequently seen but not used?

The post Using Array reduce appeared first on David Walsh Blog.

Nahoru
Tento web používá k poskytování služeb a analýze návštěvnosti soubory cookie. Používáním tohoto webu s tímto souhlasíte. Další informace