Skip to content

Instantly share code, notes, and snippets.

@cange
Created January 13, 2013 19:54
Show Gist options
  • Save cange/4525890 to your computer and use it in GitHub Desktop.
Save cange/4525890 to your computer and use it in GitHub Desktop.
Pure JavaScript Flatten Array extension
/**
@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