When you splicing, just decrease your loop index.
There were many good suggestions, I will send the code for different parameters, and you can decide what to use
Splice Reduction Index 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 back 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 a 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 these 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) with Array.filter. precision Array.filter. Putting elements into a new array was also slow compared to Array.slice . See http://jsperf.com/clean-undefined-values-from-array2
I am really surprised to see that IE leads the package here, and to see Chrome behind FF and IE. I donโt think I have ever done a test with this result.