Created
December 8, 2016 17:00
-
-
Save fczuardi/ecf4c18f0424d517425cdce69bc0cc3d to your computer and use it in GitHub Desktop.
interview question: implement array flatten
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
| // unwraps one level by accumulating the | |
| // array concatenation of one item with the next item | |
| const unwrap = arr => arr.reduce((acc, item) => acc.concat(item), []); | |
| // flattens an array with nested array items | |
| const flatten = arr => { | |
| const needsUnwrapping = arr.filter( i => Array.isArray(i)).length > 0; | |
| if (!needsUnwrapping) { | |
| return arr; | |
| } | |
| return flatten(unwrap(arr)); | |
| }; | |
| // ------ | |
| //tests | |
| const a = [[1], [2], [3], [4]]; | |
| const b = [1, [2], [[3, [4]]]]; | |
| const c = [[1, 2, [3]], 4]; | |
| const answer = [1, 2, 3, 4]; | |
| const isCorrect = arr => JSON.stringify(arr) === JSON.stringify(answer); | |
| console.log(isCorrect(flatten(a))); | |
| console.log(isCorrect(flatten(b))); | |
| console.log(isCorrect(flatten(c))); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment