2

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"
1
  • Look into the splice() function Commented Apr 30, 2014 at 21:14

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

function(x){return x!=null} wouldn't be that hard to write as well
Perfect, simple and effective.
0

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++;
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.