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

soum
  • 1,131
  • 3
  • 20
  • 47

5 Answers5

4

Try something like this,

for(var i = 0; i < x.length; i++){
    if (x[i] !== null){
      numberCollection.push(x[i]);
    }
}
Lumi Lu
  • 3,289
  • 1
  • 11
  • 21
  • beat me by 34 seconds. – FreeSandwiches Apr 29 '15 at 02:18
  • @ScottCorbett -- this one works..your work too. I see where my mistake was. Thanks for pointing at the right direction :-) – soum Apr 29 '15 at 02:26
  • Just curious, why `!==` instead of just `!=`? The type comparison seems unnecessary in this case... – Matt Browne Apr 29 '15 at 02:32
  • 1
    @MattBrowne. Here http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons the link maybe have better explaining. thanks. – Lumi Lu Apr 29 '15 at 02:34
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.

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.

Matt Browne
  • 12,169
  • 4
  • 59
  • 75
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);
0

This should work.

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