Skip to content
Related Articles
Open in App
Not now

Related Articles

How to truncate an array in JavaScript ?

Improve Article
Save Article
  • Last Updated : 13 Dec, 2022
Improve Article
Save Article

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.

Using array.length property: Using Javascript`s 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 the array.length property according to the required output.

Example: In this example, we will see the basic use of Javascript`s array.length property.

Javascript




<script>
    const num = [1, 2, 3, 4, 5, 6];
    num.length = 3;
    console.log( num );
</script>


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 exist 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: In this example, we will see the truncating of an array using Javascript`s array.splice method.

Javascript




<script>
    const num = [1, 2, 3, 4, 5, 6];
    num.splice(4);
    console.log(num);
</script>


Output:

[1, 2, 3, 4]

The above are the 2 ways using which you can truncate an array in JavaScript.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!