DEV Community

Discussion on: Quick Tip: Transform an Array into an Object using .reduce()

Collapse
 
qm3ster profile image
Mihail Malo

That's a really cool fully immutable solution.
I understand it, but I would personally avoid it in JS, if not for readability by juniors then at least because I have an addiction to micro optimization.

const idsByCategory = posts => {
  const categories = new Map() // I prefer Map
  for (const { category, id } of posts) {
    const existing = categories.get(category)
    if (!existing) categories.set(category, [id])
    else existing.push(id)
  }
  return categories
}


// This is what Prettier does to it
const categoryPosts = posts.reduce(
  (acc, { id, category }) => ({
    ...acc,
    [category]: [...(acc[category] || []), id]
  }),
  {}
)

// Yes, this is short.
const categoryPosts = posts.reduce((acc, { id, category }) => ({...acc, [category]: [...(acc[category] || []), id]}), {})