Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop last element of javascript array when array reaches specific length

I would like to cache some data in javascript, but the cache should be limited to 10 elements for example.

I can place the objects in javascript array, but what is the best way to keep the array limited to 10 elements?

Example:

function getData(dataId) { return new NextDataObject(dataId); }

var array = new Array();

array.push(getData(0));
array.push(getData(1));
(...)
array.push(getData(10)); // this should result in dropping "oldest" data, so getData(0) should be removed from the array, so that in array there are only 10 objects at maximum

Should such mechanism be written manually (using splice() for example?) or are there better ways to achieve such "cache" structure in javascript?

BTW: in this particular situation I'm using angular.

like image 348
walkeros Avatar asked Jun 24 '15 09:06

walkeros


People also ask

How can you remove the last item in an array in JavaScript?

The pop() method removes (pops) the last element of an array. The pop() method changes the original array. The pop() method returns the removed element.

Which method removes the last element from the end of an array?

The Array pop() method is the simplest method used to remove the last element in an array. The pop() method returns the removed element from the original array.

How do I remove a specific element from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do you target the last element of an array?

To get the last item, we can access the last item based on its index: const finalElement = animals[2] ; JavaScrip arrays are zero-indexed.


1 Answers

Override the push function of your caching array.

var array = new Array()
array.push = function (){
    if (this.length >= 10) {
        this.shift();
    }
    return Array.prototype.push.apply(this,arguments);
}

Plunker


To make this more reusable I created a method which returns new instance of such array (basing on above code).

function getArrayWithLimitedLength(length) {
    var array = new Array();

    array.push = function () {
        if (this.length >= length) {
            this.shift();
        }
        return Array.prototype.push.apply(this,arguments);
    }

    return array;

}

var array = getArrayWithLimitedLength(10);
like image 178
Michael Avatar answered Oct 12 '22 15:10

Michael