Tell us what’s happening:
what is wrong with this code?..test cases are not passing…although m getting output same as the expected output
Your code so far
var new_arr=[];
function steamrollArray(arr) {
for(var i=0;i<arr.length;i++){
if(!Array.isArray(arr[i]))
new_arr.push(arr[i]);
else steamrollArray(arr[i]);
}
return new_arr;
}
steamrollArray([1, {}, [3, [[4]]]]);
Your browser information:
Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36
.
Link to the challenge:
https://www.freecodecamp.org/challenges/steamroller
Hi @ABHI5995
Your logic is fine, the problem is you’re declaring the new_arr
variable in the global scope, so when the tests run in sequence, they all add to the same array in memory which ultimately pollutes the answer.
You can test this by commenting out your call to steamrollArray
and re-running the tests, the first one should pass then the last 3 should fail.
1 Like
yuppp now i understood the issue…can u help me in getting out of it?
You could create a function inside the steamrollArray
function that wraps the for loop. Then declare the new_arr
variable inside steamrollArray
and call the nested function before the return statement, passing in the array to it.
Kinda like this if your stuck on the implementation:
function steamrollArray(arr) {
var new_arr=[];
function steamRoll(arr) {
for(var i=0;i<arr.length;i++){
if(!Array.isArray(arr[i]))
new_arr.push(arr[i]);
else steamRoll(arr[i]);
}
}
steamRoll(arr);
return new_arr;
}
Alternatively, rather than mutating an array, you could look at doing something functional, like using reduce. You should be able to adapt your existing code fairly easily to use reduce.