Skip to content

Instantly share code, notes, and snippets.

@roboli
Last active November 16, 2017 14:23
Show Gist options
  • Save roboli/7db0b2b29aa971620e851ad7a318fc49 to your computer and use it in GitHub Desktop.
Save roboli/7db0b2b29aa971620e851ad7a318fc49 to your computer and use it in GitHub Desktop.
const flatten = (array) => {
// Concat nested arrays recursively
const f = (arr, acc) => {
if(arr.length > 0) {
const first = arr[0];
if(Array.isArray(first)) {
// Item is an array, start new call
acc = acc.concat(f(first, []));
} else {
// Add iem to accumulator
acc.push(first);
}
// Continue with next item
return f(arr.slice(1), acc);
} else {
// Nothing to do, return accumulator
return acc;
}
};
// Start
return f(array, []);
};
// console.log('Result:',flatten([1, [2, 3], 4, [5, [6, [7, 8]]], 9, 0]));
module.exports = flatten;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment