I’m working on “Intermediate Algorithm Scripting: Steam Roller”. I can pass all tests except the last, because I am not able to take an empty object { } from an array and push it to an empty array that will contain my final set of elements to be returned.
Here is my algorithm:
function steamrollArray(arr) {
let box = [];
let firstArr = [...arr];
two(firstArr);
function two(arr2){
for(let i = 0; i < arr2.length; i++) {
if(arr2[i] === {} || typeof(arr2[i]) === "number" || typeof(arr2[i]) === "string") { box.push(arr2[i]);}
else {
two(arr2[i]);
}
}
// console.log(box);
}
return box;
}
steamrollArray([1, [2], [3, [[4]]]]);
The problem in my code lies in this part of my conditional: if(arr2[i] === {}) {box.push(arr2[i])};
I think other elements which are not empty objects are passing this conditional when I do not want them to.
^ Note: I’ve solved the algorithm another way using Array.isArray. I just would like to know how to solve this problem using the method pasted above so I can better understand my error and how to identify an empty object in the future. Thanks in advance…