Skip to content

Instantly share code, notes, and snippets.

@thibblen
Created May 1, 2014 14:35
Show Gist options
  • Save thibblen/d89a897ae0106287a82a to your computer and use it in GitHub Desktop.
Save thibblen/d89a897ae0106287a82a to your computer and use it in GitHub Desktop.
// This function fails, results are at the bottom.
var flatten = function (array) {
var result = [],
currentElem;
for (var i=0, len=array.length; i<len; i++){
currentElem = array[i];
if (Array.isArray(currentElem)) {
// The result of flatten(array) is an array, why isn't is combined with the
// previous array by the concat method ?
result.concat(flatten(currentElem));
} else {
result.push(currentElem);
}
}
return result;
};
// Results
console.log(flatten([1,2,3,[4,5]])); // => [1,2,3]
console.log(flatten([[1,2,3],["a","b","c"],[1,2,3]])); // => []
console.log(flatten([[[1,2,3]]])); // => []
// This function works, results are at the bottom
var flatten = function (array) {
var result = [],
currentElem;
for (var i=0, len=array.length; i<len; i++){
currentElem = array[i];
if (Array.isArray(currentElem)) {
// This is the part that is different
(flatten(currentElem)).forEach(function (v) {
result.push(v);
});
} else {
result.push(currentElem);
}
}
return result;
};
// Results
console.log(flatten([1,2,3,[4,5]])); // [1,2,3,4,5]
console.log(flatten([[1,2,3],["a","b","c"],[1,2,3]])); // [1,2,3,"a","b","c",1,2,3]
console.log(flatten([[[1,2,3]]])); // [[1,2,3]]

I tried to write a function that would flatten nested arrays but my solution did not work when I used the Array.prototype.concat method. As a work around, I used the Array.prototype.forEach method and it worked as expected. Both implimentations are below.
Does you know why .concat() doesn't work?

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