Skip to content

Instantly share code, notes, and snippets.

@gaastonsr
Created March 7, 2017 03:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gaastonsr/756f0273a35ce6bbfca8d5e6d21e2c38 to your computer and use it in GitHub Desktop.
Save gaastonsr/756f0273a35ce6bbfca8d5e6d21e2c38 to your computer and use it in GitHub Desktop.
Flatten Array
const assert = require('assert');
function flattenArray(array) {
return array.reduce((acc, current) => {
if (Array.isArray(current)) {
return acc.concat(flattenArray(current));
}
return acc.concat([current]);
}, []);
}
function emptyArrayTest() {
const test = [];
const result = flattenArray(test);
const expected = [];
assert.deepEqual(result, expected);
}
emptyArrayTest();
function noNestingTest() {
const test = [1, 2, 3];
const result = flattenArray(test);
const expected = [1, 2, 3];
assert.deepEqual(result, expected);
}
noNestingTest();
function deeplyNestedTest() {
const test = [[1, [2, [[3, 4], [5]]], [6]]];
const result = flattenArray(test);
const expected = [1, 2, 3, 4, 5, 6];
assert.deepEqual(result, expected);
}
deeplyNestedTest();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment