spaceDog
spaceDog

Reputation: 461

How come the code stopped checking if is an Array?

I am trying to write flatten an array, but how come it stopped checking when the code reached nested Array? It is out putting this [ 1, 2, 3, [ [ [Object] ] ] ].

Please explain why it stopped going through nested Array and why it isn't concating. Thanks

flatten = function(nestedArray, result) {
    result = [];

    each(nestedArray, function(item){

      if(Array.isArray(item)){
          result = result.concat(item);
      } else {
          result.push(item);
      }
    });
return result;
};

flatten([1, [2], [3, [[[4]]]]])

Upvotes: 0

Views: 61

Answers (2)

Aswathy S
Aswathy S

Reputation: 731

function pushfn(element,index, array){

if(Array.isArray(element)){
  element.forEach(pushfn);
}
else{
 result.push(element);
}

};

result = [];
var nestedArray = [1, [2], [3, [[[4]]]]];
nestedArray.forEach(pushfn);

console.log(result);

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115242

There is no method like each in JavaScript, what you can do is use Array#forEach with recursion function.

var flatten = function(nestedArray, result) {
  result = [];
  // iterate over array
  nestedArray.forEach(function(item) {
    if (Array.isArray(item)) {
      // do recursion to flatten the inner array and concatenate
      result = result.concat(flatten(item));
    } else {
      result.push(item);
    }
  });
  return result;
};

console.log(flatten([1, [2], [3, [[[4]]]]]));

Upvotes: 2

Related Questions