limit array size javascript

How to limit array size with JavaScript

In this blog post, we are going to look at how to limit array size with javascript. To limit array size we will use the ‘Array.splice()’ method.

Let’s see how we can limit array size in javascript with an example.

// Limit array size with JavaScript

const myArray = ["a", "b", "c", "d", "e"];

function addElement(arr, element, arrSize) {
  return [element, ...arr.splice(0, arrSize - 1)];
}

console.log(addElement(myArray, "z", 5));

// Output: ['z', 'a', 'b', 'c', 'd']

In the above example, we have declared a constant ‘myArray’ which holds an array of elements. And we have written the ‘addElement’ function to add a new element to our array. This function takes three parameters arr, element, and arrSize.

Inside the ‘addElement’ function, we are prepending the new element to our array. We are removing the extra element in our array using the ‘Array.splice()’ method.

The final array which is returned by the ‘addElement’ function will be of size ‘arrSize’ which we passed to it.

That’s it. This is a simple example. Hope it helped.

Leave a Comment

Your email address will not be published. Required fields are marked *