DEV Community

Discussion on: Reduce is not my best friend(anymore)

Collapse
alfredosalzillo profile image
Alfredo Salzillo ๐Ÿบ

Your problem is that you were using reduce to push all the results in the same object.

To collect you can use Object.assign

function extractData(records) {
  return Object.assign({}, ...records.map(({ id, ...rest}) => ({
    [id]: computeRestFields(rest),
  })));
}
// or
function extractData(records) {
  return records.map(({ id, ...rest}) => ({
    [id]: computeRestFields(rest),
  })).reduce(Object.assign, {});
}

or Object.fromEntries

function extractData(records) {
  return Object.fromEntries(records.map(({ id, ...rest}) => [id, computeRestFields(rest)]));
}
Collapse
lucastrvsn profile image
Lucas Trevisan

I noticed this as well.

Reduce this many fields at the same object will blow your memory

Collapse
klvenky profile image
Venkatesh KL Author

Exactly! I've seen it going crazy high

Collapse
klvenky profile image
Venkatesh KL Author

Yeah, I realized that soon after. Thanks