In this article, we will learn how to truncate an array in JavaScript by reducing its length and keeping only the required elements.
Approach 1: Using length Property
The length property can be directly modified to reduce the size of an array. Setting it to a smaller value removes all elements beyond the specified length.
Example: In this example, we truncate the array to its first three elements by changing its length property.
const arr = [1, 2, 3, 4, 5, 6];
arr.length = 3;
console.log(arr);
Output
[ 1, 2, 3 ]
Approach 2: Using splice() Method
The splice() method can remove all elements from a specified index to the end of an array. It modifies the original array.
Example: In this example, we remove all elements starting from index 4.
const arr = [1, 2, 3, 4, 5, 6];
arr.splice(4);
console.log(arr);
Output
[ 1, 2, 3, 4 ]
Approach 3: Using slice() Method
The slice() method creates a new array containing elements from the specified range. Unlike splice(), it does not modify the original array.
Example: In this example, we use slice() to keep only the first two elements.
const arr = ["Geeks", "Geek", "GFG", "gfg", "G"];
const result = arr.slice(0, 2);
console.log(result);
Output
[ 'Geeks', 'Geek' ]
Approach 4: Using pop() in a Loop
The pop() method removes the last element from an array. By calling it repeatedly, we can remove elements until the array reaches the desired length.
Example: In this example, we remove elements from the end until the array contains three elements.
const arr = [1, 2, 3, 4, 5];
const len = 3;
while (arr.length > len) {
arr.pop();
}
console.log(arr);
Output
[ 1, 2, 3 ]
Output
GeeksforGeeks is a computer...Approach 5: Using filter() Method
The filter() method creates a new array containing elements that satisfy a condition. By checking the index, we can keep only the required number of elements.
Example: In this example, we use filter() to keep the first three elements of the array.
const arr = [1, 2, 3, 4, 5, 6];
const result = arr.filter((element, index) => index < 3);
console.log(result);
Output
[ 1, 2, 3 ]