Last active
February 23, 2018 22:20
-
-
Save ralucas/ca642513dbd3fcbaa35e1c041d73e502 to your computer and use it in GitHub Desktop.
Flatten on Array.prototype
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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