Categories
JavaScript Answers

How to truncate an array with JavaScript?

Spread the love

To truncate an array with JavaScript, we use the 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 return an array with the arr array items between index 0 and 3.

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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