Created
April 13, 2015 23:59
-
-
Save jamesmartin/ccdc35d003a85f09b9b1 to your computer and use it in GitHub Desktop.
Flatten an Array in Javascript
This file contains 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
exports.first = function(l) { | |
return l[0] | |
}; | |
exports.rest = function(l) { | |
return l.reduce(function(accumulator, item, index) { | |
if(index > 0) { | |
accumulator.push(item); | |
} | |
return accumulator; | |
}, []); | |
}; | |
exports.flatten = function(l, accumulator){ | |
if(l.length == 0) { | |
return accumulator; | |
} else { | |
var head = exports.first(l); | |
if(Array.isArray(head)) { | |
return exports.flatten(head, accumulator); | |
} else { | |
accumulator.push(head); | |
return exports.flatten(exports.rest(l), accumulator); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use in node.js: