1

I am trying to construct an array looping over another array which more or less looks like this

var x = [1, null, 324, 110, null]

I am trying to loop over this and check if an item at index i is not null then it goes into a new array

var numberCollection = [];

for(var i = 0; i < x.length; i++){
    numberCollection[i] = (!!x[i]) ? x[i];
}

console.log(numberCollection)

which definitely does not work. What am I missing? I saw some examples of deleting an invalid item from an array but that is out of scope in this context

5 Answers 5

4

Try something like this,

for(var i = 0; i < x.length; i++){
    if (x[i] !== null){
      numberCollection.push(x[i]);
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

beat me by 34 seconds.
@ScottCorbett -- this one works..your work too. I see where my mistake was. Thanks for pointing at the right direction :-)
Just curious, why !== instead of just !=? The type comparison seems unnecessary in this case...
@MattBrowne. Here stackoverflow.com/questions/359494/… the link maybe have better explaining. thanks.
0

Let's call the first array(the one that has NULLs) A[] and the second B[]. we will also need an int count.

for(var i=0; i<A.length; i++){
    if(A[i] != NULL){
        B[count] = A[i];
        count++;
    }
}

that should do it.

Comments

0

The other answers work...just to give you another option, you could use the new filter() method introduced in ECMAScript 5:

var numberCollection = x.filter(function(item) {
    return !!item;
});

Note that for this to work in IE8 and below you'll need to provide a shim for the filter() method; there's one here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Polyfill.

Comments

0

The following seemed to work fine.

var x = [1, null, 324, 110, null];
var numberCollection = [];

var k = 0;
for(i = 0; i < x.length; i++) {
    if (x[i] === null) {
        continue;
    } else {
        numberCollection[k++] = x[i];
    }
}

console.log(numberCollection);

Comments

0

This should work.

var numberCollection = [];
for(var i = 0, j = x.length; i < j; i++){
    if (x[i] !== null) {numberCollection.push(x[i])}
}

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.