2

Is there an easy way to make an array have a specific amount of element. In the sense that if you push more into it, it overides the first element.

for example i want an array to only contain 2 elements. if i push a third element, it should overwrite the earliest element (the first in). Like a stack.

4
  • While it may be possible, it's not advisable. It's much wiser to use your own data structure (that uses an array internally) to accomplish this. Commented Nov 17, 2016 at 8:03
  • see this stackoverflow.com/questions/7727919/creating-a-fixed-size-stack <br/> Make something similar to this in javascript Commented Nov 17, 2016 at 8:04
  • a stack would remove the first element and pushes on top. Commented Nov 17, 2016 at 8:07
  • You will have to use Array subclassing to create a new array which has it's own push method in it's prototype to suppress / shadow the push method of the Array.prototype. It's own push method should take care of the shifting out the item at index 0 operation once the length reaches to a certain value. Commented Nov 17, 2016 at 8:36

2 Answers 2

0

You could use a counter and use the modulo with the wanted length for inserting.

function push(array, length) {
    var counter = 0;
    return function (value) {
        array[counter % length] = value;
        counter++;
    };
}

var array = [],
    pushToArray = push(array, 2);

pushToArray(1);
console.log(array);

pushToArray(2);
console.log(array);

pushToArray(3);
console.log(array);

pushToArray(4)
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

0

So as i have commented above you might do this by array sub-classing. The following snippet introduces a new Array structure with two new methods as last and push. However our new push shadows the real push method of the Array.prototype. The new push takes the first argument as the limit to the array length such as [1,2,3].push(4,"a","b","c") will limit the length to 4 and the result would be [3,"a","b","c"]. The return value will be the deleted elements in an array as we are using splice under the hood.

function SubArray(...a) {
  Object.setPrototypeOf(a, SubArray.prototype);
  return a;
}
SubArray.prototype = Object.create(Array.prototype);
SubArray.prototype.last = function() {
  return this[this.length - 1];
};
SubArray.prototype.push = function(lim,...a){
  Array.prototype.push.apply(this,a);
  return this.splice(0,this.length-lim);
};

myArray = new SubArray(1,2,3);
myArray.last();
myArray.push(4,"a","b","c");
console.log(myArray);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.