Created
November 1, 2016 12:11
-
-
Save gkucmierz/16c5e2b74a1e409884c5d3e7e95563bd to your computer and use it in GitHub Desktop.
Flatten array from desired level
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Flatten array from desired level | |
| let flattenArray = function(arr, lvl = 0) { | |
| if (!(arr instanceof Array)) return lvl === 0 ? arr : [arr]; | |
| if (lvl > 0) { | |
| return arr.map((el) => flattenArray(el, lvl-1)); | |
| } else { | |
| return arr.reduce((arr, el) => { | |
| return arr.concat(flattenArray(el, lvl-1)); | |
| }, []); | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment