javascript - JS array concatenation for results of recursive flattening -


good day!

task flat version of array, may include amount of nested arrays other elements. input [1, [2], [3, [[4]]]] output [1, 2, 3, 4] expected. freecodecamp spoiler alert. naturally, recursive solution comes mind, e.g.:

function steamrollarray(arr) {   var result = [];   for(var = 0; < arr.length; i++){       //part of interest       if (array.isarray(arr[i])){         var nestedelements = steamrollarray(arr[i]);         for(var j = 0; j < nestedelements.length; j ++){           result.push(nestedelements[j]);         }       //</part of interest>.       } else {         console.log("pushing: " + arr[i]);         result.push(arr[i]);       }   }   return result; } 

and it's thing. result of sample run be:

pushing: 1 pushing: 2 pushing: 3 pushing: 4 [1, 2, 3, 4] 

and question is: goes awry, when use concat add nestedelements (that supposedly store return result of recursive call). if change first if{} block in for loop (marked part of interest) snippet below:

if (array.isarray(arr[i])){     var nestedelements = steamrollarray(arr[i]);     result.concat(nestedelements); } else { 

we observe following result:

pushing: 1 pushing: 2 pushing: 3 pushing: 4 [1] 

my understanding pass result of each recursive call concat function, add returned array result, reason it's not case. questions on task asked, this one, concerned flattening algorithm part, not questioned here. still fail see answer causes difference. might overlooked in hassle or result of limited experience. sorry if that's case.

array#concat returns new array result.

the concat() method returns new array comprised of array on called joined array(s) and/or value(s) provided arguments.

so need assign result:

result = result.concat(nestedelements); // ^^^^^^ assignment 

Comments