Question

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"
Was it helpful?

Solution

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.

OTHER TIPS

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++;
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top