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?
Created
May 1, 2014 14:35
-
-
Save thibblen/d89a897ae0106287a82a to your computer and use it in GitHub Desktop.
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
// 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 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
// 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]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment