Skip to content

Instantly share code, notes, and snippets.

@uriklar
Created August 22, 2017 13:42
Show Gist options
  • Save uriklar/5a5c3c1dc2124552cf78690309123e56 to your computer and use it in GitHub Desktop.
Save uriklar/5a5c3c1dc2124552cf78690309123e56 to your computer and use it in GitHub Desktop.
Function that recursively flattens an array in vanilla JS with tests
function recursivelyFlatten(array) {
if (!array) {
return []
}
var result = [];
if (Array.isArray(array)) {
array.forEach((value) => {
result = result.concat(recursivelyFlatten(value));
});
} else {
result = [array];
}
return result
}
function runTest(input, output, message) {
var expected = JSON.stringify(output);
var actual = JSON.stringify(recursivelyFlatten(input));
if ( actual !== expected) {
throw message + ' expected: ' + expected + ', got: ' + actual;
}
console.log(message, '✔');
}
const testSuit = {
withEmptyArray: () => runTest([], [], 'should return empty array if array is empty'),
zeroLevelsDeep: () => runTest([1,2,3], [1,2,3], 'should flatten array zero levels deep'),
multipleLevelsDeep: () => runTest([[1,2,[3]],4], [1,2,3,4], 'should flatten array multple levels deep'),
ignoreEmptyArrays: () => runTest([[], [1,2], [3, []], 4], [1,2,3,4], 'should ignore empty arrays')
}
Object.keys(testSuit).forEach((test) => testSuit[test]());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment