Skip to content

Instantly share code, notes, and snippets.

@robertovg
Created January 5, 2018 17:05
Show Gist options
  • Save robertovg/b0cea85f352f506e4eac3b72e3b5360c to your computer and use it in GitHub Desktop.
Save robertovg/b0cea85f352f506e4eac3b72e3b5360c to your computer and use it in GitHub Desktop.
Function to flat arrays
// const a = [1, [], [2, 3, [4],
// [5],
// [1, 2, 3, 4, [5, [6],
// [4], [],
// ]]
// ], 3, 6];
// const b = [1, 2, 3];
/**
* Function to flat arrays
*/
function flatArray(array = []) {
// We reduce the original array to a flat new array
return array.reduce(
(acu, curr) =>
// If the current element is not array
(!Array.isArray(curr) ?
// Then just continue adding elements to our array
[...acu, curr] :
// If it's an array, we just flat this position of the array
[...acu, ...flatArray(curr)])
, []
);
}
// console.log(a);
// console.log(flatArray(a));
// console.log('-');
// console.log(b);
// console.log(flatArray(b));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment