Murplyx Murplyx - 5 months ago 21
Javascript Question

Limit array size

Let's say I have an array with data elements, in this example numbers, like this:

var a = [432, 238, 122, 883, 983];


And I want to limit the array, so that everytime I add an element to the array, it always keeps a length of let's say 7, or less and removes the oldest elements.

My current aproach looks like this:

function add(x) {
a.unshift(x);
a = a.slice(0, 7);
}


It works just fine, but isn't there a more elegant way to do it, like one line or something?

Edit:
By "more elegant" I mean so that I don't need the add function and just easily could inline the code where I need it, without typing out a for example three times, and only having one line would also make the code "clearer"

Answer

Just to add another possible alternative:

a = [x, ...a.slice(0, 6)];

Even though I would personally choose Nina Scholz's solution (with a "better" condition for changing length and for older environments where ES6 is not supported)

References: