Good afternoon! I am looking to create a fixed array of length 5, where I want to store recent viewed ids. And when it reaches the limit to delete elements from the end.
For example:
array = ['5', '4', '3', '2', '1'] // Array of 5 with ID's
When I add an id the array want to be like this:
array = ['6', '5', '4', '3', '2'];
And keep going.
Thank you so much for taking your time and I respect your help.
Heres a function that takes an id, removes the last element if there is more than 5 and then add the id to the start of the array.
function addId(id, array) {
if (array.length === 5) {
array.pop();
}
array = array.splice(0, 0, id);
return array;
}
You could unshift the array and adjust the length by the minimum of the wanted length and the old length.
function unshift(array, value) {
array.unshift(value);
array.length = Math.min(array.length, 5);
return array;
}
var array = [],
i;
for (i = 0; i < 10; i++) console.log(unshift(array, i).join(' '));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With