[javascript] 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: '/' });
}

This question is related to javascript jquery cookies

The answer is


I think you could just do:

let array = [];
array.length = 2;
Object.defineProperty(array, 'length', {writable:false});


array[0] = 1 // [1, undefined]

array[1] = 2 // [1, 2]

array[2] = 3 // [1, 2] -> doesn't add anything and fails silently

array.push("something"); //but this throws an Uncaught TypeError

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

You need to actually use the shortened array after you remove items from it. You are ignoring the shortened array.

You convert the cookie into an array. You reduce the length of the array and then you never use that shortened array. Instead, you just use the old cookie (the unshortened one).

You should convert the shortened array back to a string with .join(",") and then use it for the new cookie instead of using old_cookie which is not shortened.

You may also not be using .splice() correctly, but I don't know exactly what your objective is for shortening the array. You can read about the exact function of .splice() here.


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

This soultion works better in an 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().


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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to cookies

SameSite warning Chrome 77 How to fix "set SameSite cookie to none" warning? Set cookies for cross origin requests Make Axios send cookies in its requests automatically How can I set a cookie in react? Fetch API with Cookie How to use cookies in Python Requests How to set cookies in laravel 5 independently inside controller Where does Chrome store cookies? Sending cookies with postman