Created
August 4, 2012 09:37
-
-
Save JaHIY/3256397 to your computer and use it in GitHub Desktop.
JavaScript:multidimensional arrays to one dimensional array
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
/* Recursion Method */ | |
function toArray(array) { | |
var result=[]; | |
function toarray(array) { | |
for (var l=array.length,i=0;i<l;i++) { | |
if (Array.isArray(array[i])) { | |
toarray(array[i]); | |
} else { | |
result.push(array[i]); | |
} | |
} | |
return result; | |
} | |
return toarray(array); | |
} | |
/* Stack Method */ | |
function toArray(array) { | |
var result=[], stack=[], p; | |
stack.push(array); | |
while (stack.length !== 0) { | |
p = stack.pop(); | |
if (Array.isArray(p)) { | |
stack = stack.concat(p); | |
} else { | |
result.push(p); | |
} | |
} | |
return result.reverse(); | |
} | |
/* Queue Method */ | |
function toArray(array) { | |
var result=[], queue=[], p; | |
queue.push(array); | |
while (queue.length !== 0) { | |
p = queue.shift(); | |
if (Array.isArray(p)) { | |
queue = p.concat(queue); | |
} else { | |
result.push(p); | |
} | |
} | |
return result; | |
} | |
/* splice Method from @xnreformer */ | |
function A(a){ | |
var r=a.concat(), /* make a copy */ | |
i=0; | |
while (i<r.length) { | |
if (Array.isArray(r[i])) { | |
r.splice.apply(r,[i,1].concat(r[i])); | |
} else { | |
i++; | |
} | |
} | |
return r; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment