Skip to content

Instantly share code, notes, and snippets.

@jamesmartin
Created April 13, 2015 23:59
Show Gist options
  • Save jamesmartin/ccdc35d003a85f09b9b1 to your computer and use it in GitHub Desktop.
Save jamesmartin/ccdc35d003a85f09b9b1 to your computer and use it in GitHub Desktop.
Flatten an Array in Javascript
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);
}
}
};
@jamesmartin
Copy link
Author

Use in node.js:

> var x = require('./flatten.js');
> x.flatten([1, 2], [])
[ 1, 2 ]
> x.flatten([1, [2,3]], [])
[ 1, 2, 3 ]
> x.flatten([1, [2,3, [4, 5, 6]]], [])
[ 1, 2, 3, 4, 5, 6 ]
> x.flatten([1, [2,3, [4, 5, [6]]]], [])
[ 1, 2, 3, 4, 5, 6 ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment