I’m trying to solve an exercise where I need to create the function cleanArray and remove various items from an array. This is as far as I could get
function cleanArray(arr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === null || 0 || "" || false || undefined) {
arr.splice(i, 1);
return arr
}
}
}
But this only filters out null
for me. I’ve tried putting the items to remove in a separate array or going one by one, but then it either returns undefined
or only filters out the 0 even when it’s not the first item to remove.
I’ve seen other answers where people use filter
or indexOf
but I want to see if there’s a way to do it with splice
. Is it not possible to use the logical operators here?
This is not the way you make multiple comparisons. Your if condition can be written as:
Now it is clear why it doesn’t work, right? You need to compare
arr[i]
to every one of these values:Note: this approach probably won’t work. Since you are removing elements from your array (and hence it is getting shorter and shorter), once an element is removed, you will be in the wrong index, and by the time you reach the end of your loop, you will encounter undefined index errors. Finally, move your return statement out of the loop.
I suggest
If you want to stay away from
Array.filter()
, I suggest creating a new array and only pushing in the values you want:You could simplify this doing two simple steps.
Example: