Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed Array and when it reaches the limit remove elements from the end - Javascript

Tags:

javascript

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.

like image 661
REWA Avatar asked Oct 17 '25 06:10

REWA


2 Answers

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;
}
like image 132
dotconnor Avatar answered Oct 19 '25 20:10

dotconnor


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(' '));
like image 34
Nina Scholz Avatar answered Oct 19 '25 22:10

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!