Ben Muircroft Ben Muircroft - 1 year ago 68
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=[];

//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.

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
will be instant instead...

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


Why is my array now

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 Source

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[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);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download