Let's say I have an array with data elements, in this example the numbers are, for example:
var a = [432, 238, 122, 883, 983];
And I want to limit the array, so that every time I add an element to the array, it always keeps let say say 7 or less and removes the oldest elements.
My current aproach is as follows:
function add(x) { a.unshift(x); a = a.slice(0, 7); }
This works fine, but is there a more elegant way to do this, as a single line or something else?
Edit: By "more elegant," I mean that I donβt need the add function, and I can just embed the code I need without printing, for example, three times, and only one line will also make the code more understandable "
javascript arrays
super
source share