Can I limit the length of an array in JavaScript?

I want to display the product browsing history, so I am storing the product ids in a browser cookie.

Because the list of history is limited to 5 items, I convert the cookie value to an array, then check the length of it and cut the redundant.

The code below is what I have tried, but it does not work; the array item isn't removed.

I would like to ask how to limit the array length so it can only store 5 items?

Or

How can I cut the items after the array index 4?

var id = product_id;
var browseHistory = $.cookie('history');
if (browseHistory != null) {
  var old_cookie = $.cookie('history');
  var new_cookie = '';

  if (old_cookie.indexOf(',') != -1) {
    var arr = old_cookie.split(',');
    if (arr.length >= 5) {
      arr.splice(4, 1)
    }
  }

  new_cookie = id + ',' + old_cookie;
  $.cookie('history', new_cookie, { expires: 7, path: '/' });
} else {
  $.cookie('history', id, { expires: 7, path: '/' });
}

Solution 1:

You're not using splice correctly:

arr.splice(4, 1)

this will remove 1 item at index 4. see here

I think you want to use slice:

arr.slice(0,5)

this will return elements in position 0 through 4.

This assumes all the rest of your code (cookies etc) works correctly

Solution 2:

The fastest and simplest way is by setting the .length property to the desired length:

arr.length = 4;

This is also the desired way to reset/empty arrays:

arr.length = 0;

Caveat: setting this property can also make the array longer than it is: If its length is 2, running arr.length = 4 will add two undefined items to it. Perhaps add a condition:

if (arr.length > 4) arr.length = 4;

Alternatively:

arr.length = Math.min(arr.length, 4);

Solution 3:

arr.length = Math.min(arr.length, 5)

Solution 4:

var  arrLength = arr.length;
if(arrLength > maxNumber){
    arr.splice( 0, arrLength - maxNumber);
}

This solution works better in a dynamic environment like p5js. I put this inside the draw call and it clamps the length of the array dynamically.

The problem with

arr.slice(0,5)

is that it only takes a fixed number of items off the array per draw frame, which won't be able to keep the array size constant if your user can add multiple items.

The problem with

if (arr.length > 4) arr.length = 4;

is that it takes items off the end of the array, so which won't cycle through the array if you are also adding to the end with push().