Limit Array Size
Let's say I have an array with data elements, in this example numbers, like this: var a = [432, 238, 122, 883, 983]; And I want to limit the array, so that everytime I add an elem
Solution 1:
Just to add another possible alternative:
a = [x, ...a.slice(0, 6)];
Even though I would personally choose Nina Scholz's solution (with a "better" condition for changing length and for older environments where ES6 is not supported)
References:
Solution 2:
Just adjust the length property after pushing.
functionadd(x) {
a.unshift(x);
a.length = a.length < 7 ? a.length : 7;
}
The cleanes way is to check before
functionadd(x) {
a.unshift(x);
if (a.length > 7) {
a.length = 7;
}
}
Solution 3:
You can check the length of array when adding and Shift it (remove the first element) if the length has passed:
function add(x) {
a.push(x);
if (a.length > 7)
a.shift();
}
Solution 4:
a=add(188);
function add(x){
a.push(x);
return a.slice(1);
}
Solution 5:
You can also use Array.pop. Also if you wish to add a property to array, you can make it generic.
Array.prototype.Limit_push = function(x) {
this.unshift(x);
if (this.maxLength !== undefined && this.length > this.maxLength)
this.pop();
}
var a = [];
a.maxLength = 7for (var i = 0; i < 10; i++) {
a.Limit_push(i);
console.log(a)
}
var b = [];
for (var i = 0; i < 10; i++) {
b.Limit_push(i);
console.log(b)
}
Post a Comment for "Limit Array Size"