The Wayback Machine - https://web.archive.org/web/20240917110604/https://www.geeksforgeeks.org/how-to-truncate-an-array-in-javascript/
Open In App

How to truncate an array in JavaScript ?

Last Updated : 30 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

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.

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 ]

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' ]

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

Using Array.prototype.pop() in a loop

To truncate an array using `Array.prototype.pop()` in a loop, iterate backward over the array and use `pop()` to remove elements until the desired length is reached. This approach modifies the original array by removing elements from the end.

Example: In this example we defines an array and a length to keep, then removes elements from the array using a loop and pop until the array has the desired length, finally logging the modified array.

JavaScript
const array = [1, 2, 3, 4, 5];
const lengthToKeep = 3;

for (let i = 0; i < array.length - lengthToKeep; i++) {
    array.pop();
}

console.log(array);

Output
[ 1, 2, 3, 4 ]

Using filter() Method

The filter() method creates a new array with all elements that pass the test implemented by the provided function. By using the index as a condition, you can effectively truncate the array.

Example: In this example, we will see how to truncate an array using the filter() method.

JavaScript
const num = [1, 2, 3, 4, 5, 6];
const truncatedNum = num.filter((element, index) => index < 3);
console.log(truncatedNum);

Output
[ 1, 2, 3 ]

Using Proxy Objects to Control Array Length

A Proxy object allows you to define custom behavior for fundamental operations on an object, including arrays. By using a Proxy, you can create a controlled environment where truncation behavior can be applied based on dynamic conditions.

  1. Create a Proxy Handler: Define a handler with traps for array operations like get and set.
  2. Intercept Array Length Changes: Control how the length property is set, effectively truncating the array when the length is adjusted.

Example:

JavaScript
function createTruncatedArray(arr, maxLength) {
    const handler = {
        get(target, prop) {
            if (prop === 'length') {
                return Math.min(target.length, maxLength);
            }
            if (prop in target) {
                const index = Number(prop);
                if (index < maxLength) {
                    return target[prop];
                }
                return undefined; // Return undefined for out-of-bounds indices
            }
            return undefined; // Return undefined for non-existent properties
        },
        set(target, prop, value) {
            if (prop === 'length') {
                const newLength = Number(value);
                if (newLength < maxLength) {
                    target.length = newLength; // Adjust the array length
                } else {
                    target.length = maxLength; // Ensure length does not exceed maxLength
                }
            } else {
                if (Number(prop) < maxLength) {
                    target[prop] = value;
                }
            }
            return true; // Indicate successful assignment
        }
    };

    return new Proxy(arr, handler);
}
const originalArray = [1, 2, 3, 4, 5];
const maxLength = 3;
const truncatedArray = createTruncatedArray(originalArray, maxLength);

console.log(truncatedArray);
console.log(truncatedArray.length); // Output: 3

// Modify the array
truncatedArray[2] = 10;
console.log(truncatedArray);

// Attempt to access or set an out-of-bounds index
console.log(truncatedArray[3]);
truncatedArray[4] = 20;
console.log(truncatedArray); 

Output
[ 1, 2, 3, 4, 5 ]
3
[ 1, 2, 10, 4, 5 ]
undefined
[ 1, 2, 10, 4, 5 ]



Similar Reads

JavaScript Program to Truncate a String to a Certain Length and Add Ellipsis (...)
In this article, we will see how to truncate a string to a certain length and add an ellipsis (...) in JavaScript. To truncate a string to a specific length and add an ellipsis (...) in JavaScript means shortening the string to a predefined character count, indicating that the content continues beyond the truncated portion. There are several method
3 min read
JavaScript Program to Truncate a String to a Certain Length
In this article, we are going to learn how can we truncate a string to a certain length. Truncating a string to a certain length in JavaScript means shortening a string so that it doesn't exceed a specified maximum length. This can be useful for displaying text in user interfaces, such as titles or descriptions while ensuring that the text does not
3 min read
How to Truncate a String in JavaScript ?
In JavaScript, there are several ways to truncate a string which means cutting off a part of the string to limit its length. Truncating a string is useful when we want to display only a certain number of the characters in the user interfaces such as previewing a longer text or ensuring that text fits within the specified space. Use the below method
2 min read
How to truncate text in Angular2?
Approach: It is easy to truncate text in Angular. The truncated text helps us to remove or cut-off portions of text. It abruptly ends the text, reducing the length of the text. It removes text in accordance with the truncate function used. Syntax: String length is greater than the given characters. function(str, length, ending) {........} String tr
2 min read
Node.js fs.truncate() Method
The fs.truncate() method in node.js is used to change the size of the file i.e either increase or decrease the file size. This method changes the length of the file at the path by len bytes. If len represents a length shorter than the file's current length, the file is truncated to that length. If it is greater than the file length is padded by app
2 min read
Node.js fsPromises.truncate() Method
The fsPromises.truncate() method in node.js is used to change the size of the file i.e. either increase or decrease the file size. This method changes the length of the file at the path by len bytes. If len represents a length shorter than the file’s current length, the file is truncated to that length. If it is greater than the file length is padd
2 min read
Node.js fsPromises.truncate() Method
The fsPromises.truncate() method is defined in the File System module of Node.js. The File System module is basically used to interact with the hard-disk of the user's computer. The truncate() method is used to modify the inner contents of the file by 'len' bytes. If len is shorter than the file’s current length, the file is truncated to that lengt
3 min read
Node.js filehandle.truncate() Method
The filehandle.truncate() method is defined in the File System module of Node.js. The File System module is basically to interact with the hard disk of the user’s computer. The truncate() method used to modify the inner contents of the file by ‘len’ bytes. If len is shorter than the file’s current length, the file is truncated to that length of len
3 min read
How to operate callback-based fs.truncate() method with promises in Node.js ?
The fs.truncate() method defined in the File System module of Node.js. The File System module is basically to interact with the hard disk of the user’s computer. The truncate() method is used to modify the inner contents of the file by ‘len’ bytes. If len is shorter than the file’s current length, the file is truncated to that length of len and If
4 min read
Node.js fs.filehandle.truncate() Method
The fs.filehandle.truncate() method is an inbuilt application programming interface of class fs.filehandle within File System module which is used to truncate the particular file object and only that much byte will be retained which passed as an integer in truncate() method. Syntax: const filehandle.truncate(len) Parameter: This method takes the le
3 min read
Lodash _.truncate() Method
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc. The _.truncate() method of String in lodash is used to truncate the stated string if it is longer than the specified string length. The last characters of the string which are truncated are replaced with the st
2 min read
Truncate a String using filter in Vue.js
In this article, we are going to learn how to truncate strings using filters in VueJS. Filters are a functionality provided by Vue components that let you apply formatting and transformations to any part of your template dynamic data. The filter property of the component is an object. A single filter is a function that accepts a value and returns a
2 min read
How to truncate a file using Node.js ?
In this article, we are going to explore How to truncate the complete file using Node. There are two methods to truncate the file of all its data. We can either use the fs.truncate() method or the fs.writeFile() method to replace all the file content. Method 1: The fs.truncate() method in Node.js can be used for changing the file size, i.e. this me
3 min read
Primer CSS Truncate Expand on Hover or Focus
Primer CSS is a free open-source CSS framework that is built upon systems that create the foundation of the basic style elements such as spacing, typography, and color. This systematic method makes sure our patterns are steady and interoperable with every other. Its approach to CSS is influenced by Object-Oriented CSS principles, functional CSS, an
3 min read
Primer CSS Truncate Custom Max Widths
Primer CSS is a free open-source CSS framework that is built upon systems that create the foundation of the basic style elements such as spacing, typography, and color. This systematic method makes sure our patterns are steady and interoperable with every other. Its approach to CSS is influenced by Object-Oriented CSS principles, functional CSS, an
3 min read
Primer CSS Truncate
Primer CSS is a CSS framework that comes with pre-styled components and a design language with spacing, typography, and Theming that helps in building a website effectively. This systematic method makes sure our patterns are steady and interoperable with every other. It is created with GitHub’s design system. Primer CSS truncate is used to shorten
2 min read
Primer CSS Truncate Multiple Items
Primer CSS is a free open-source CSS framework that is built upon systems that create the foundation of the basic style elements such as spacing, typography, and color. This systematic method makes sure our patterns are steady and interoperable with every other. Its approach to CSS is influenced by object-oriented CSS principles, functional CSS, an
2 min read
How to truncate the text using Angular Pipe and Slice ?
Angular Pipe and Slice can be used to manipulate or transform the data in a specific format. Angular Pipes can be utilized to format or transform data directly before displaying it in the Angular template. The Slice is a built-in method in JavaScript that enables the users to extract a part of the array or string without modifying the original data
3 min read
Text truncate in CSS
CSS Text truncation allows you to control how much text overflows its container due to the distortion of the layout at the end of your design, making such text awkward. This is typically accomplished by adding an ellipsis (...) to the end of the text to denote that the text has been truncated. It is also fairly important for responsive design, prov
5 min read
How to extend an existing array with another array without creating a new array in JavaScript ?
JavaScript arrays are a powerful data structure that allows you to store and manipulate collections of data. Often, we may need to combine or extend two or more arrays into a single array. It's easy to create a new array by concatenating two or more arrays but if we want to extend an existing array without creating a new array. There are two easy w
2 min read
How to compare two JavaScript array objects using jQuery/JavaScript ?
In this article, we are given two JavaScript array/array objects and the task is to compare the equality of both array objects. These are the methods to compare two JavaScript array objects: Using jQuery not() methodUse the sort() functionUse JSON.stringify() functionUsing every() and indexOf()Using Lodash _.isEqual() MethodApproach 1: Using jQuery
3 min read
How to get the elements of one array which are not present in another array using JavaScript?
The task is to get the elements of one array that are not present in another array. Here we are going to use JavaScript to achieve the goal. Here are a few techniques discussed. Approach Take the arrays in variables.Use the .filter() method on the first array and check if the elements of the first array are not present in the second array, Include
2 min read
What’s the difference between “Array()” and “[]” while declaring a JavaScript array?
Consider the below codes: var myArray = new Array(5); and var myArray = [5]; Though these two lines might appear the same, but it is not the case. Consider the below explanations: Case 1: var myArray = new Array(5) This method is used to define an array of length 5. The parameter passed here '5' is an argument that defines the initial length of the
2 min read
How to check whether an array is subset of another array using JavaScript ?
The task is to check whether an array is a subset of another array with the help of JavaScript. There are a few approaches, we will discuss below: Approaches:using JavaScript array.every() methodusing JavaScript array.some() methodApproach 1: Using JavaScript array.every() methodThis approach checks whether every element of the second array is pres
2 min read
Difference between array.size() and array.length in JavaScript
The array.size() method is functionally equivalent to the array.length property and it can be only used in jQuery. Here in JavaScript array.size() is invalid method so array.length property should be used. Below examples implement the above concept: Example 1: This example demonstrates array.size() method and array.length property. C/C++ Code &lt;!
3 min read
How to write a program that takes a predicate and array, like Array.filter(), but only keeps x if pred(x) === false in JavaScript ?
The predicate in JavaScript is the same as the predicate maths which returns true or false. The predicate is just like a function that determines whether the passed arguments satisfy the given condition or not. The predicate returns only true or false. In this article, let us see the working of the predicate with arrays when it is passed with a fun
3 min read
Javascript Program to Find array sum using Bitwise OR after splitting given array in two halves after K circular shifts
Given an array A[] of length N, where N is an even number, the task is to answer Q independent queries where each query consists of a positive integer K representing the number of circular shifts performed on the array and find the sum of elements by performing Bitwise OR operation on the divided array.Note: Each query begins with the original arra
5 min read
Javascript Program to Check if it is possible to make array increasing or decreasing by rotating the array
Given an array arr[] of N distinct elements, the task is to check if it is possible to make the array increasing or decreasing by rotating the array in any direction.Examples: Input: arr[] = {4, 5, 6, 2, 3} Output: Yes Array can be rotated as {2, 3, 4, 5, 6}Input: arr[] = {1, 2, 4, 3, 5} Output: No Approach: There are four possibilities: If the arr
4 min read
How to create an array of elements, ungrouping the elements in an array produced by zip in JavaScript ?
We can create an array of elements by ungrouping the elements in an array produced by zip by using different methods in JavaScript such as Math.max(), array specific methods namely Array.prototype.map(), Array.prototype.reduce() and Array.prototype.forEach(). This operation can also be termed as unzip. Before looking at unzip, let us understand wha
2 min read
JavaScript Program to Construct an Array from its pair-sum Array
The pair-sum array is a unique construction that holds the sum of all potential pairs of elements from the original array. At first glance, it might appear to be challenging, but in this article, we'll Construct an array from its pair-sum array and discover some of its most intriguing uses. What is Pair - Sum Array?A pair-sum array in JavaScript is
4 min read