Sergei Basharov Sergei Basharov - 2 years ago 65
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 Source

You might be looking for something like this:

if(arr.length === 100) {

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download