DEV Community

How to elegantly flatten a list

YCM Jason on October 04, 2017

The problem Given any list xs, where xs could contain other lists or any non-list values, we wish to extract all the values in xs. For e...
Collapse
 
markotaponen profile image
Marko Taponen

In order to understand recursion one must understand recursion.

Collapse
 
ycmjason profile image
YCM Jason

my favourite quote of all time!

Collapse
 
sebastianr1982 profile image
Sebastian Rapetti • Edited

Hi!
PHP do not have native functions for flatten.
Link below, my php functions:
gist.github.com/s3b4stian/0e2e638a...

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])], []);
}