How to truncate an array in JavaScript ?
In JavaScript, there are two ways of truncating an array. One of them is using length property and the other one is using splice() method. In this article we will see, how we can truncate an array in JavaScript using both these methods.
- length Property
- splice() Method
Using array.length property: Using array.length property, you can alter the length of the array. It helps you to decide the length up to which you want the array elements to appear in the output.
Syntax:
// n = number of elements you want to print var_name.length = n;
In the above syntax, you can assign the size to the array using array.length property according to the required output.
Example:
Javascript
Output:
[1, 2, 3]
As you can see in the above output, only three elements get printed. Assigning a value to the array.length property truncates the array and only the first n values exists after the program.
Using splice() Method: The splice() method removes items from an array, and returns the removed items.
Syntax:
// n=number of elements you want to print var_name.splice(n);
Example:
Javascript
Output:
[1, 2, 3, 4]
The above are the 2 ways using which you can truncate an array in JavaScript.
Join the conversation