Created
January 13, 2013 19:54
-
-
Save cange/4525890 to your computer and use it in GitHub Desktop.
Pure JavaScript Flatten Array extension
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
/** | |
@see http://tech.karbassi.com/2009/12/17/pure-javascript-flatten-array/ | |
// usage | |
var given = [[1, [2, [3, [4, [5, [6, [7, [8, [9, [0]]]]]]]]]]]; | |
var value = given.flatten(); | |
'value' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] | |
*/ | |
Array.prototype.flatten = function () { | |
var flat = [], | |
i = 0, | |
len = this.length | |
; | |
for (; i < l; i++) { | |
var type = Object.prototype.toString.call(this[i]).split(' ').pop().split(']').shift().toLowerCase(); | |
if (type) { | |
flat = flat.concat(/^(array|collection|arguments|object)$/.test(type) ? this[i].flatten() : this[i]); | |
} | |
} | |
return flat; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment