Reputation: 381
If I have an array with three text values and two null values. How could those be removed with a loop. Is it possible to use splice to do this.
arrayVal[0] = null
arrayVal[1] = "Some text"
arrayVal[2] = null
arrayVal[3] = "More text"
arrayVal[4] = "Text Again"
I want to achieve the following:
arrayVal[0] = "Some Text"
arrayVal[1] = "More text"
arrayVal[2] = "Text Again"
Upvotes: 2
Views: 1438
Reputation: 7884
This can also be achieved with a for
loop;
function removeNull() {
var arrayVal, newArrayVal, j;
for (var i = 0; i < arrayVal.length; i++) {
j = 0;
if (arrayVal[i]) {
newArrayVal[j] = arrayVal[i];
j++;
}
}
}
Upvotes: 0
Reputation: 94101
Here's a way to do it:
arrayVal.filter(Boolean);
Note that Boolean will remove any falsy value, that includes zero, empty string, null, undefined.
Upvotes: 6