Ben Muircroft Ben Muircroft - 2 months ago 8
Javascript Question

Slicing Array - "unexpected item in the bagging area?"

I want to create an array that is blank up-until an index (example 700)

var a=[];
a[700]=true;

//produces [700:true].length==700


then every time I randomly add another index (very close to the last maybe 702,703,699...)

I want to (on each new index) keep the length of the array as the highest index number but get rid of every index that is not in the top ten highest indexes.

a
for
loop (where a[i]=null on everything apart from the last 10 indexes) is out of the question as this array's last index could be a rather large number that would cause iteration code to hang too long!

So I figured
Array.slice
will be instant instead...

What I am not understanding is if my array is length 700 and I do:

a=a.slice(a.length-10,a.length-1);


Why is my array now
[700:true].length==701
?




Please vote to close - it looks like this is a bug with my version of chrome as other people are not getting the same console output as I am!

Answer

To get rid of the true values that are not in the last 10 indexes, you could iterate the true elements with forEach, which only visits entries that exist. Then with delete you can delete those entries:

a.forEach ((v, i, a) => {
    if (i < a.length - 10) delete a[i];
});

var a=[];

a[700]=true;
a[702]=true;
a[699]=true;
a[692]=true; // this one should be removed

// clean-up:
a.forEach ((v, i, a) => {
    if (i < a.length - 10) delete a[i];
});

// show last 13 elements:
for (var i=a.length-13; i<a.length; i++) {
    console.log (i, a[i]);
}
// output length
console.log('length: ', a.length);