Skip to content

Instantly share code, notes, and snippets.

@nomadrat
Created January 29, 2019 15:10
Show Gist options
  • Save nomadrat/cf835b238bac58b15e45dce258025667 to your computer and use it in GitHub Desktop.
Save nomadrat/cf835b238bac58b15e45dce258025667 to your computer and use it in GitHub Desktop.
function flatten(inputArray) {
/**
* One can argue that it's a good idea to validate inputArray
* value here, but i disagree. In this exact case it's better
* to not reinvent the wheel — if inputArray is not an Array
* application will throw error anyway at .reduce step
*/
return inputArray.reduce((accumulator, current) => {
if (Array.isArray(current)) {
return [
...accumulator,
...flatten(current)
];
} else {
// can also be done via accumulator.concat(current)
return [
...accumulator,
current
];
}
}, []);
}
console.log(flatten([1,3,[5, [9,10, [11,22]]]]));
console.log(flatten([]));
console.log(flatten([1,3]));
console.log(flatten([1,3,[5, [9,10]]]));
console.log(flatten([89, [3, 5], 1, [[17, 11]]]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment