Skip to content

Instantly share code, notes, and snippets.

@orafaelfragoso
Created February 20, 2018 17:55
Show Gist options
  • Save orafaelfragoso/76d47131cbaa6bc4fe76183663869b49 to your computer and use it in GitHub Desktop.
Save orafaelfragoso/76d47131cbaa6bc4fe76183663869b49 to your computer and use it in GitHub Desktop.
Flatten an Array with JS
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