Deep flatten and housekeeping

Changed original flatten to be named deepFlatten, added normal flatten, improved some other snippets.
This commit is contained in:
Angelos Chalaris
2017-12-12 18:12:24 +02:00
parent 721e1f1d79
commit d44e228e14
5 changed files with 32 additions and 16 deletions

View File

@ -1,10 +1,8 @@
### Flatten array
Use recursion.
Use `reduce()` to get all elements that are not arrays, flatten each element that is an array.
Use `reduce()` to get all elements inside the array and `concat()` to flatten them.
```js
const flatten = arr =>
arr.reduce( (a, v) => a.concat( Array.isArray(v) ? flatten(v) : v ), []);
// flatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]
const flatten = arr => arr.reduce( (a, v) => a.concat(v), []);
// flatten([1,[2],3,4) -> [1,2,3,4]
```