Created
July 31, 2015 11:50
-
-
Save skamenetskiy/696c35f67e4287988fff to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#!/usr/local/bin/node | |
/** | |
* Converts current array to flat array | |
* @returns {Array} | |
*/ | |
Array.prototype.flatten = function () { | |
/** | |
* The result container | |
* @type {Array} | |
*/ | |
var result = []; | |
// Go through array items recursively and flatten them | |
this.forEach(function (item) { | |
if (item instanceof Array) { | |
return item | |
.flatten() | |
.forEach(function (item) { | |
result.push(item) | |
}) | |
} | |
result.push(item) | |
}); | |
return result | |
}; | |
/** | |
* The provided example | |
* @type {Number[]} | |
*/ | |
var exampleArray = [[1, 2, [3]], 4]; | |
console.log(exampleArray.flatten()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment