REWA
REWA

Reputation: 135

Fixed Array and when it reaches the limit remove elements from the end - 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.

Upvotes: 4

Views: 3792

Answers (6)

dotconnor
dotconnor

Reputation: 1786

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;
}

Upvotes: 5

Mark
Mark

Reputation: 92460

You can use proxies to do this and a lot more. For example here's a simple proxy that keeps an array to only 5 elements. This has the advantage that it still acts like an array with length and map and all the other stuff.

This is set so when you unshift, extra elements will fall off the end. You could of course do the opposite with push. You can also manually assign by index so long as the index is less than 5.

var limitedArrayProxy = {
    set: function(target, property, value, receiver) {
      if (!isNaN(property)){
          if(parseInt(property) < 5){
            target[property] = value;
      }
    }
      return true;
    }
  };
  
var limitArray = new Proxy( [], limitedArrayProxy );

// push on a few elements 
limitArray.push(1, 2, 3)
console.log(limitArray)

// unshift a few more
limitArray.unshift(5, 4)
console.log(limitArray)

// now that length is 5 unshift will add to front
// and the last element will fall off
limitArray.unshift(10)
console.log(limitArray)

// manually change index 2
limitArray[2] = "manually changed"
console.log(limitArray)

// it won't let you push more than five
limitArray.push(20)
console.log(limitArray)

// can't add an index of 5 or greater
limitArray[5] = "overflow"
console.log("still 5 element:", limitArray)

// it still acts like an array 
// with length and methods like map
console.log("length", limitArray.length)
console.log("map squares", limitArray.map(i => i**2))

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386736

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(' '));

Upvotes: 2

Unmitigated
Unmitigated

Reputation: 89412

You can modify the Array's push method to remove the last element of the Array with Array.prototype.pop if its length is equal to the maximum length that you want to the Array to be.

var array = ['5', '4', '3', '2', '1'];
array.maxlength = 5;
array.push = function(elem){
  if(this.length==this.maxlength){
    this.pop();
  }
  return [].unshift.call(this, elem);
}
array.push('6');
console.log(array);

Upvotes: 1

Katie.Sun
Katie.Sun

Reputation: 711

var array = ['5', '4', '3', '2', '1'];

console.log(array);
queue('6');
console.log(array);

function queue(number){
    array.pop(); //removes last element from array
    array.splice(0, 0, number);//puts new number in first spot
}

This should do the trick. Any time you needed to add an element to the array you would just call that function.

Upvotes: 1

baao
baao

Reputation: 73251

You could create a little class managing the ids for you

class Ids {
  constructor() {
    this._store = [];
  }

  add(id) {
    if (this.store.length > 4) this._store.shift();
    this._store.push(id);
  }

  get store() {
    return this._store;
  }
}

const id = new Ids();
id.add(1);
id.add(2);
id.add(3);
id.add(4);
id.add(5);
id.add(6);
id.add(7);
id.add(8);
id.add(9);
console.log(id.store);

Upvotes: 0

Related Questions