Open In App

How to truncate an array in JavaScript ?

Last Updated : 09 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 these methods.

These are the following ways to truncate an array:

Approach 1: Using length Property

Using Javascript 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
let_name.length = n;

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

Javascript




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


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.

Approach 2: 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




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


Output

[ 1, 2, 3, 4 ]

Approach 3: Using slice() Method

The Javascript arr.slice() method returns a new array containing a portion of the array on which it is implemented. The original remains unchanged.

Syntax:

arr.slice(begin, end)

Example: In this example, we will see the use of the slice() method.

Javascript




let arr = ["Geeksforgeeks", "Geek", "GFG", "gfg","G"];
arr = arr.slice(0, 2);
console.log(arr);


Output

[ 'Geeksforgeeks', 'Geek' ]

Approach 4: Using Lodash _.truncate() Method

The _.truncate() method of String in lodash is used to truncate the stated string if it is longer than the specified string length. 

Syntax:

_.truncate([string=''], [options={}])

Example: In this example, we are using Lodash _.truncate() Method

Javascript




// Requiring lodash library
const _ = require('lodash');
 
// Calling _.truncate() method with
// its parameter
let res = _.truncate(
'GeeksforGeeks is a computer science portal.');
 
// Displays output
console.log(res);


Output:

GeeksforGeeks is a computer...


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads