DEV Community

Discussion on: You Might Not Need Lodash

Collapse
 
masaeedu profile image
Asad Saeeduddin

It's a little confusing to simultaneously use reduce and push. Use reduce when you're actually computing a new value, use a for of loop when you're mutating things in a loop.

// Use this
const flattened = as => as.reduce((p, c) => [...p, ...c], [])

// Or this
const flattened = []
for (const item of as) {
  flattened.push(...item)
}
Collapse
 
gsonderby profile image
Gert Sønderby

Your first example chokes on [1,[2,3,[4]],5,[6,7]], throwing an error. Worse, on ['yo',['dawg','I',['herd']],'you',['like','arrays']] it breaks in a number of interesting ways, spreading some strings, failing to spread some arrays.

Thread Thread
 
masaeedu profile image
Asad Saeeduddin

It is an implementation of the join function for arrays, and works with arrays of arrays, not arrays of mixed objects.

If you need it to work with mixed objects you'll need a recursive call (or ap+pure):

const flattened = as => as.reduce((p, c) => [...p, ...(Array.isArray(c) ? flattened(c) : [c])], [])

Anyway, the point is to avoid mutation in the reduce, whatever it is you may be implementing.

Thread Thread
 
gsonderby profile image
Gert Sønderby

At this point it honestly seems like you're just trying to score points against me, in some way. I am disinterested in continuing that.

Thread Thread
 
masaeedu profile image
Asad Saeeduddin

Sorry to hear you feel that way. I was just suggesting that using mutation in reduce is confusing, didn't mean for it to turn into this long-running back and forth.

Collapse
 
gsonderby profile image
Gert Sønderby

The array I am pushing to is the accumulator of the reduce call, though. I'm pushing the elements of each array found, once flattened.

It works like a classic head/tail recursion, if an element is an array it first gets flattened itself, then it's elements are pushed onto the accumulator.

Thread Thread
 
masaeedu profile image
Asad Saeeduddin

That's fine, but as I said, it's confusing to use reduce and mutation simultaneously. You're passing [] as a seed value, so the only thing that got mutated was that seed array. If you'd used array.reduce((flatArray, item) => ...) without the seed value (which would be fine but for the mutation), it would end up filling the first item in the input array you were passed.

In general it's easier on the fallible human developer to make mutation look like mutation and pure computation look like pure computation.

Thread Thread
 
gsonderby profile image
Gert Sønderby

The only way it would matter here is if you somehow changed the function to make flatArray available while the function was running. I'm not even sure how you'd do that. But I do want to point your attention to the words, used above: "quick and dirty"...