9
I am trying to create a function that files an array to another newArray. If one of the array elements is an array
, I want to map all its subelements to newArray.
Therefore:
var array = [1,2,3,4,5, [1,3,2,4,1]]
Should return
[1,2,3,4,5,1,3,2,4,1]
My code is like this:
var array = [1,2,3,4,5, [1,3,2,4,1]]
var newArray = array.map(function(element){
if (typeof(element) === "object"){
element.forEach(function(subElement){
return(subElement);
})
} else {
return(element);
}
})
newArray;
But newArray returns:
[ 1, 2, 3, 4, 5, Undefined ]
Hugo, can you tell me what’s wrong with my algorithm?
– Kvera
When
typeof(element) === "object"
the callback ofmap
returnsundefined
because there is noreturn
. The Return inside the foreach doesn’t count - it makes the foreach callback return, not the map callback. In short: you can’t solve this problem with magic, you have to do recursion anyway.– hugomg
Your answer performs best among recursives: http://jsperf.com/flatten-de-array-em-javascript
– bfavaretto
@bfavaretto also added a recursive function: http://jsperf.com/flatten-de-array-em-javascript/2 Hugo:
+1
for wasting my time improving my response :)– Sergio