Reputation: 2245
I am creating an array in Javascript where the product id is used for the key. As the key is numeric, the array is filling gaps with null.
So for example, if I had only two products and their ids were 5 and 7, I would do something like:
var arr = []
arr[5] = 'my first product';
arr[7] = 'my second product';
This array is then passed to a PHP script but upon printing the array, I get the following;
Array (
[0] = null
[1] = null
[2] = null
[3] = null
[4] = null
[5] = My first product
[6] = null
[7] = My second product
)
my ID numbers are actually 6 digits long, so when looping over the array, there are 100,000 iterations, even if I actually only have two products.
How can I create the array so the null values are not entered? I thought of making the key a string instead but as the array is build dynamically, I am not sure how to do that.
var arr = [];
for(var i=0; i<products.length; i++)
{
array[products[i].id] = products[i].name;
}
Thanks
Upvotes: 1
Views: 63
Reputation: 705
var arr = []
arr[5] = 'my first product';
arr[7] = 'my second product';
let result = arr.filter(ar => ar != null);
console.log(result);
Upvotes: 0
Reputation: 386578
For iterating the array, you could use Array#forEach
, which skips sparse items.
var array = [];
array[5] = 'my first product';
array[7] = 'my second product';
array.forEach(function (a, i) {
console.log(i, a);
});
For better organisation, you could use an object, with direct access with the given id.
{
5: 'my first product',
7: 'my second product'
}
Upvotes: 1
Reputation: 14541
Forcing javascript key integer fills array with null
You are declaring an empty array and then setting values into 6th and 8th element in the array. That leaves the values of other elements as null.
If you don't intend to push
items into array, i.e. use objects. Something like,
var obj = {};
obj[5] = "my first product";
obj[7] = "my second product";
This means the object created is:
obj = {"5":"my first product","7":"my second product"}
Upvotes: 0