How to truncate an array in JavaScript ?
Last Updated :
30 Aug, 2024
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 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);
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.
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);
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' ]
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);
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);
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.
- Create a Proxy Handler: Define a handler with traps for array operations like
get and set. - 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 ]
Please Login to comment...