Last active
July 12, 2017 12:58
-
-
Save aliaspooryorik/5aa4d5ca48a759c86cb9f679e1b6e310 to your computer and use it in GitHub Desktop.
Flatten an 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
<cfscript> | |
a = [1,[2,[3,[4,5],6,7],8,9],10]; | |
function recurse(data) { | |
var result = []; | |
data.each(function(item) { | |
if (isArray(item)) { | |
result.append(recurse(item), true); | |
} else { | |
result.append(item); | |
} | |
}); | |
return result; | |
} | |
function looping(data) { | |
var result = []; | |
var clone = []; | |
arrayAppend(clone, data, true); | |
while (clone.len()) { | |
var item = clone[1]; | |
clone.deleteAt(1); | |
if (isArray(item)) { | |
clone.append(item, true); | |
} else { | |
result.append(item); | |
} | |
} | |
return result; | |
} | |
function reduce(data) { | |
return data.reduce(function(result, item) { | |
if (isArray(item)) { | |
return result.append(reduce(item), true); | |
} | |
return result.append(item); | |
}, []); | |
} | |
writeDump(recurse(a)); | |
writeDump(looping(a)); | |
writeDump(reduce(a)); | |
</cfscript> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment