Reputation: 1159
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
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
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
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
Reputation: 3305
Try something like this,
for(var i = 0; i < x.length; i++){
if (x[i] !== null){
numberCollection.push(x[i]);
}
}
Upvotes: 4
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