DEV Community

Discussion on: How to elegantly flatten a list

Collapse
 
maroun_baydoun profile image
Maroun Baydoun • Edited

What do you think about my solution? Flatten an array in JavaScript

Collapse
 
ycmjason profile image
YCM Jason • Edited

It is interesting! There are a few points about your solution:

  1. checking array should be done with Array.isArray() (here)
  2. I think it would be better if you take the base case outside your reducer function.

If I were going to define flatten with reduce, I would have written something like the following:

function flatten(xs){
  if(xs.length === 0) return [];
  return xs.reduce((acc, x) => [...acc, ...(Array.isArray(x)? flatten(x):
 [x])], []);
}