How to truncate an array with JavaScript?

Sometimes, we want to truncate an array with JavaScript.

In this article, we’ll look at how to truncate an array with JavaScript.

How to truncate an array with JavaScript?

To truncate an array with JavaScript, we can use the array slice method.

For instance, we write

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr = arr.slice(0, 4);
console.log(arr);

to call arr.slice with 0 and 4 to get an array with the first 4 items of arr.

Then we assign the returned array back to arr to update it.

Conclusion

To truncate an array with JavaScript, we can use the array slice method.