Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all undefined keys from a javascript array (hopefully when creating the array?)

I have placed my frustrations into a jsfiddle to observe here: http://jsfiddle.net/8ShFr/1/

var brand_new_array = new Array();
brand_new_array[10] = "random array value";
alert('why does this array have a length of ' + brand_new_array.length + '???');

I am doing some calculations client side that require me to set javascript array keys of 1M+ in number.

Not knowing exactly what that number is demands that I iterate through the first 1M+ empty array values before getting to an array key that holds data.

I simply want to set a single large key value for a javascript array without creating a bunch of empty keys before it?

I am using jQuery.each to iterate over the array, and it keeps going through array[0], array[1], array[2], etc... when I only set array[123125] for example.

like image 271
darkAsPitch Avatar asked Dec 05 '22 07:12

darkAsPitch


1 Answers

Just filter out the undefineds.

brand_new_array = brand_new_array.filter(function(n){return n !== undefined}); 
like image 89
Oleg Avatar answered Dec 06 '22 21:12

Oleg