soum
soum

Reputation: 1159

construct a new array from an array by filtering out null items

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

Upvotes: 1

Views: 42

Answers (5)

HDN
HDN

Reputation: 54

This should work.

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

Upvotes: 0

deluged.oblivion
deluged.oblivion

Reputation: 134

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);

Upvotes: 0

Matt Browne
Matt Browne

Reputation: 12419

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.

Upvotes: 0

Lumi Lu
Lumi Lu

Reputation: 3305

Try something like this,

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

Upvotes: 4

FreeSandwiches
FreeSandwiches

Reputation: 136

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.

Upvotes: 0

Related Questions