re: 10 JavaScript array methods you should know VIEW POST

TOP OF THREAD FULL DISCUSSION
re: My personal tip is learn .reduce as soon as possible. It intimidated me for a long time and I used .forEach a lot. Once you get reduce you'll sudde...
 

Isn't reduce mainly for working with current values and a total value? How would that take the place of something like .forEach() entirely?

Granted, I do think I have a use case for it, but I don't yet see the need for replacing something like .forEach() or .map() entirely.

 

I'd say it complements them, not replaces (especially map). By example:

const snakeToCamel = str => str.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase());

const camelizeKeys = (obj) =>
  Object.keys(obj)
    .map(k => ({ [snakeToCamel(k)]: obj[k] }))
    .reduce((acc, o) => Object.assign(acc, o), {});

note that using forEach, map, and reduce is much slower than simple for loop. But unless you transform thousands of objects it probably doesn't matter.

Thanks for mentioning performance, though I avoid for loops for stuff like this now after too many times having the loop somehow end up using only the last value in the array for all iterations.

 

My main use case for using .forEach before discovering .reduce was because I wanted to transform one object into a new object with a different shape. I'd create an empty object and then .forEach the original object's Object.entities/keys to add properties to the empty object, whereas this is more concise by simply using a .reduce

code of conduct - report abuse