DEV Community


Posted on

A Quick JS Reduction: My possibly-too-clever way to reduce an array into one object in javascript

Let's say you have an array of user objects, all with unique IDs, but you want to group them in a single object by their ids.

// These are your only users
const users = [
  { id: 1, name: "Paul" },
  { id: 2, name: "Ringo" },
  { id: 3, name: "George" },

An easy way to do this using Array.prototype.reduce without creating too many intermediary objects would be:

const usersGroupedById = users.reduce((res, u) => (res[] = u, res), {})

I have a feeling every linter in the world would cry linty tears upon seeing this. But honestly, I kind of like it!

Does this code offend you? How would you do this?

My alternatives were:

/// Create objects willy-nilly because they are cheap
users.reduce((res, u) => ({ ...res, []: u }), {})

// Use Object.assign to avoid spread syntax, still create a new object for every iteration
users.reduce((res, u) => Object.assign(res, { []: u }), {})

// Arguably more readable version of the featured solution
users.reduce((res, u) => {
  res[] = u;
  return res;
}, {})

Top comments (2)

avalander profile image

Not that it matters, but for the sake of offering an alternative solution I'd probably lean more towards Object.fromEntries than reduce.

Object.fromEntries( => [, u ]))
Enter fullscreen mode Exit fullscreen mode
brettimus profile image

totally matters and I wish I could heart this twice -- I've never seen Object.fromEntries!