Skip to content

Instantly share code, notes, and snippets.

@JiriChara
Last active July 8, 2019 07:02
Show Gist options
  • Save JiriChara/754a718ce14882c91ea957b77898cab2 to your computer and use it in GitHub Desktop.
Save JiriChara/754a718ce14882c91ea957b77898cab2 to your computer and use it in GitHub Desktop.
function flatten(array) {
return array.reduce((acc, current) => {
// if current element is an array call flatten method recursively
if (Array.isArray(current)) {
return acc.concat(flatten(current));
}
// otherwise just accumulate the current array
return acc.concat(current);
}, []);
};
// Test
const deepArray = [[1], [2, 3, [4]], 5];
console.assert(JSON.stringify(flatten(deepArray)) === JSON.stringify([1, 2, 3, 4, 5]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment