Sergei Basharov Sergei Basharov - 6 months ago 11
Javascript Question

Push to an array and keep the array n items long

How do I push an object to an array, then when the array becomes, say, 100 items in size, remove the first one and push again, and so on?

It could be a method, like

arr.push('log item', 100)

How do I implement it better?

Answer

You might be looking for something like this:

if(arr.length === 100) {
        arr.shift(); 
    }
arr.push(VAL);

A method more like the OP's original request, replacing the push() with a new one with the option of limiting the size of the array

Array.prototype.originalPush = Array.prototype.push;
Array.prototype.push = function(val,limit)
{
    if(limit && this.length == limit)
        this.shift();
    this.originalPush(val);
}