I am trying to return [1,2,{},3,4] without using flat() My code so far
function steamrollArray(arr) {
let myArr= arr
.join(" ")
.replace(/[\s+\W+]/g," ")
.replace(/\s+/g," ")
.split(" ")
return myArr
.map((arrr) => parseInt(arrr,10))
}
console.log(steamrollArray([1, {}, [3, [[4]]]]))
Just use recursion. No need to worry about types when you do not change them.
function cleanUp(arr, out=[]) {
arr.forEach(item => {
if (Array.isArray(item)) {
cleanUp(item, out);
} else {
out.push(item);
}
});
return out;
}
console.log(cleanUp([1, {}, [3, [[4]]]]))
You can check if the vlaue is NaN and default to zero
isNaN(arrr)?0:parseInt(arrr,10))
function steamrollArray(arr) {
let myArr= arr
.join(" ")
.replace(/[\s+\W+]/g," ")
.replace(/\s+/g," ")
.split(" ")
return myArr
.map((arrr) => isNaN(arrr)?0:parseInt(arrr,10))
}
console.log(steamrollArray([1, {}, [3, [[4]]]]))