Created
June 24, 2017 02:09
-
-
Save jacobroufa/d90a7a3756ca863462caf6ea8d4a4e6a to your computer and use it in GitHub Desktop.
Flatten arbitrary nested array of integers.
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
| var arrAllInts = [[1, 2, [3]], 4]; | |
| var arrWithOthers = [ | |
| () => {}, | |
| 2, | |
| [ 4, 'five' ], | |
| [ Array.prototype, [ | |
| {}, | |
| 6 | |
| ]] | |
| ]; | |
| var oneFour = arrAllInts.reduce(flatten, []); | |
| var twoSix = arrWithOthers.reduce(flatten, []); | |
| console.log(arrAllInts, 'should reduce to [1, 2, 3, 4]', oneFour === [1, 2, 3, 4]); | |
| console.log(arrWithOthers, 'should reduce to [2, 4, 6]', twoSix === [2, 4, 6]); | |
| function flatten (prev, item) { | |
| if (item && Number.isInteger(item)) { | |
| prev.push(item); | |
| } | |
| if (item && Array.isArray(item)) { | |
| prev = item.reduce(flatten, prev); | |
| } | |
| return prev; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment