Reputation: 1771
I was working on the steamroller problem of free code camp. I came up with two solutions: one works perfectly [1, 2, 3, 4], but the other is giving [ 4 ].
The problem asks to write a function that flatten any sort of array.
my working code:
function steamrollArray(arr) {
newArr = [];
for (i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i]) === true) {
newArr = newArr.concat(steamrollArray(arr[i]));
} else if (Array.isArray(arr[i]) === false) {
newArr.push(arr[i]);
}
}
return newArr;
}
steamrollArray([1, [2], [3, [[4]]]]);
my not working code:
function steamrollArray(arr) {
newArr = [];
for (i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i]) === true) {
newArr.push(steamrollArray(arr[i]));
} else if (Array.isArray(arr[i]) === false) {
newArr.push(arr[i]);
}
}
return newArr;
}
steamrollArray([1, [2], [3, [[4]]]]);
Can anyone explain why the second code give only [4] ?
Upvotes: 1
Views: 67
Reputation: 1294
function steamrollArray(arr) {
// I'm a steamroller, baby
let newArr = arr.slice(); //newArr is a copy of arr
var result = []; //this is going to be the flatted array
checkArray(newArr, result);
return result;
}
function checkArray(myArray, resultedArray) {
//this function is a a recursion
return myArray.map(elt => {
if (!Array.isArray(elt)) {
//so this is a simple element, it is not an array, lets push it
resultedArray.push(elt);
return elt;
} else {
return checkArray(elt, resultedArray);
}
});
}
console.log(steamrollArray([1, {},
[3, [
[4]
]]
])); // should return [1, {}, 3, 4].
Comments in the code are helpful
Upvotes: 0
Reputation: 12478
That happens because in first code, you are using
newArr = newArr.concat()
in which you are assigning it to local variable. So, even in recursion, the state will be stored.
But in second code, you are using newArr.push()
and in recursion, you are again declaring newArr=[]
;
That is the issue.
Upvotes: 1