Skip to content

Instantly share code, notes, and snippets.

@proshoumma
Last active June 22, 2017 21:06
Show Gist options
  • Save proshoumma/640d5e900d9d4495fdfb6695270154e2 to your computer and use it in GitHub Desktop.
Save proshoumma/640d5e900d9d4495fdfb6695270154e2 to your computer and use it in GitHub Desktop.
Flatten out an array
/**
* flatten out an array
* @param {Array} input
* @param {Array} [output=[]]
* @return {Array}
*/
const flatten = (input, output = []) => {
// current index
let index = output.length;
// loop through array values
for (let i = 0; i < input.length; i++) {
const value = input[i];
// check if current value is an array
if (Array.isArray(value)) {
// recursive call to flat out the array value
flatten(value, output);
} else {
// insert the value into output array
if (value) output[index++] = value;
}
}
return output;
}
// tests
console.log(flatten([1, 2, 3]));
// => [ 1, 2, 3 ]
console.log(flatten([1, 2, [[[3]]]]));
// => [ 1, 2, 3 ]
console.log(flatten([1, 2, [], [], [[[3]]]]));
// => [ 1, 2, 3 ]
console.log(flatten([1, [[2]], , [[], [4]], [[[3]]]]));
// => [ 1, 2, 4, 3 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment