Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS array apparently doesn't have a length

Hi I have come across a strange JS/JQuery issue.

I have 2 arrays which contain a timestamp and a value. I have merged these 2 arrays together so that if the timestamp is the same in both arrays create one array with the timestamp, value1 and value2. (value1 is in the first array, value2 is in the second array)

Here is the code I have written to do this. value[0] is the timestamp

var combinedArray = [];
$.each(data.new, function(key, value) {
    combinedArray[value[0]] = [value[0], value[1]];
});

$.each(data.repeat, function(key, value) {
    combinedArray[value[0]].push(value[1]);
});

If I log this to the browser it looks like so:

Image

As you can see the combinedArray does have multiple values so I'm not sure why the length is 0.

The reason this is an issue is because I need to loop over the combinedArray which I currently cannot do.

like image 559
Lukerayner Avatar asked Sep 05 '26 08:09

Lukerayner


1 Answers

As stated here the length of an array must be less than 2 to the power of 32.

Your timestamps are larger than 2 to the power of 32, so cannot be array indices.

If you create an array a = [] and assign to a particular index a[33] = 'hi' then the previous 33 values will be undefined. But if the index you assign to is greater than 2**32 then the previous values will not be created, so the length of your array will be 0.

If you use a value over 2**32 as an index it will be treated as a property instead. So, if you want you can try iterating over the properties of the array.

I suggest that instead of combinedArray[value[0]], which will create properties, the following will get you an array you can iterate over:

var combinedArray = [];
var timestampIndices = [];

$.each(data.new, function(key, value) {
    combinedArray.push([value[0], value[1]]);
    timestampIndices.push(value[0]);
});

$.each(data.repeat, function(key, value) {
    let index = timestampIndices.indexOf(value[0]);
    combinedArray[index].push(value[1]);
});
like image 157
Matt Ellen Avatar answered Sep 07 '26 21:09

Matt Ellen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!