Skip to content

Instantly share code, notes, and snippets.

@ralucas
Last active February 23, 2018 22:20
Show Gist options
  • Save ralucas/ca642513dbd3fcbaa35e1c041d73e502 to your computer and use it in GitHub Desktop.
Save ralucas/ca642513dbd3fcbaa35e1c041d73e502 to your computer and use it in GitHub Desktop.
Flatten on Array.prototype
// Flattens nested arrays down to one
// ex. [[1,[2,[3,4]]],5,[6],[[[7]]]] => [1,2,3,4,5,6,7]
Array.prototype.flatten = function flatten() {
return this.reduce(function(acc, item) {
if (Array.isArray(item) && item.some(Array.isArray)) {
return acc.concat(item.flatten());
}
return acc.concat(item);
}, []);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment