Created
February 20, 2018 17:55
-
-
Save orafaelfragoso/76d47131cbaa6bc4fe76183663869b49 to your computer and use it in GitHub Desktop.
Flatten an Array with JS
This file contains 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
const assert = require('assert'); | |
const input1 = [1, [2, 3], Object, [], 5, 6]; | |
const input2 = [1, 2, [3, 4, [5, 6, 7], 8], 9, [[10]]]; | |
const input3 = [1, 2, 3, 4, 5]; | |
function flatten(arr) { | |
return Array.isArray(arr) ? [].concat.apply([], arr.map(flatten)) : arr; | |
} | |
assert.deepEqual(flatten(input1), [1, 2, 3, Object, 5, 6]); | |
assert.deepEqual(flatten(input2), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); | |
assert.deepEqual(flatten(input3), [1, 2, 3, 4, 5]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment