Skip to content

Instantly share code, notes, and snippets.

@Carduelis
Created March 27, 2018 08:23
Show Gist options
  • Save Carduelis/862dda5ad52fab7b419f64cbe7f2a41c to your computer and use it in GitHub Desktop.
Save Carduelis/862dda5ad52fab7b419f64cbe7f2a41c to your computer and use it in GitHub Desktop.
function flatten(array) {
const flattered = [];
array.forEach(item => {
if (Array.isArray(item)) {
flattered.push(...flatten(item));
} else {
flattered.push(item);
}
})
return flattered;
}
function flatten2(array) {
return array.reduce((acc, item) => {
Array.isArray(item) ? acc.push(...flatten(item)) : acc.push(item);
return acc;
}, []);
}
const testArray = [[[1,2,[3,5,[554,5,[1, []],6]]],4]];
console.log('forEach', flatten(testArray));
console.log('reduce', flatten2(testArray));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment