When you splice, just decrement your loop index.
There were lots of good suggestions, I'll post the code for the different options and you can decide which to use
Decrement index when splicing
http://jsfiddle.net/mendesjuan/aFvVh/
var undef;
var arr = [1,2, undef, 3, 4, undef];
for (var i=0; i < arr.length; i++) {
if ( arr[i] === undef ) {
arr.splice(i,1);
i--;
}
}
Loop backwards http://jsfiddle.net/mendesjuan/aFvVh/1/
var undef;
var arr = [1,2, undef, 3, 4, undef];
for (var i=arr.length - 1; i >=0; i--) {
if ( arr[i] === undef ) {
arr.splice(i,1);
}
}
Copy to new array http://jsfiddle.net/mendesjuan/aFvVh/2/
var undef;
var arr = [1,2, undef, 3, 4, undef];
var temp = [];
for (var i=0; i < arr.length; i++) {
if ( arr[i] !== undef ) {
temp.push(arr[i])
}
}
arr = temp;
Use filter which is just a fancy way to create a new array
var undef;
var arr = [1,2, undef, 3, 4, undef];
arr = arr.filter(function(item){
return item !== undef;
});
At the end of all those examples, arr will be [1,2,3,4]
Performance
IE 11, FF and Chrome agree that Array.splice
is the fastest. 10 times (Chrome), 20 times (IE 11) as fast as Array.filter.
Putting items into a new array was also slow when compared to Array.slice
. See
http://jsperf.com/clean-undefined-values-from-array2
I am really surprised to see IE lead the pack here, and to see Chrome behind FF and IE. I don't think I've ever run a test with that result.