Created
July 27, 2016 03:09
-
-
Save rebelliard/dfaeecc299b57cb886f8a2156f45c401 to your computer and use it in GitHub Desktop.
Flatten array in JavaScript
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
// Input: | |
// [[1,2,[3]],4] | |
// Output: | |
// [1,2,3,4] | |
Array.prototype.flatten = function() { | |
return this.reduce(function(previousValue, currentValue) { | |
let value = Array.isArray(currentValue) ? currentValue.flatten() : currentValue; | |
return previousValue.concat(value); | |
}, new Array()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment