dimanche 24 novembre 2019

Flattens the nested array

function steamrollArray(arr) { let newArr = [];

arr.forEach(el => {
  if(Array.isArray(el)) {
    newArr.push(...steamrollArray(el));
  }
    newArr.push(el);  
})
return newArr; 

}

steamrollArray([1, [2], [3, [[4]]]]);

It is supposed to log the output [1, 2, 3, 4]. My question is why I have to put "else" after if-statement to make it work in the above code. I do not know why else makes some difference. Could you help me?

Aucun commentaire:

Enregistrer un commentaire