Facebook Pixel

How do you build a lookup object from an array with reduce in JavaScript?

Use an object as the initial value. For each element, set acc[element.id] = element: users.reduce((acc, u) => { acc[u.id] = u; return acc; }, {}). This gives O(1) lookup by id.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in reduce Advanced Examples: Grouping and Pipelining in JavaScript

Use an object as the initial value. For each element, push it to the array at acc[property]: people.reduce((acc, p) => { (acc[p.dept] ||= []).push(p); return acc; }, {}).

Use an object as the initial value. For each element, increment the count: arr.reduce((acc, w) => { acc[w] = (acc[w] || 0) + 1; return acc; }, {}).

Use an array of functions as the initial value: fns.reduce((acc, fn) => fn(acc), x). This applies each function in sequence to the accumulator. This is the basis of the pipe pattern.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.