How to use the splice() method In Javascript
The splice() method can be used to add or remove elements from an array. We can use it to remove all elements after the first N elements. Here, start is the starting index from where to begin deletion, and deleteCount is the number of elements to be deleted. We can set deleteCount to the length of the array to remove all elements after the first N elements.
Syntax:
array.splice(start, deleteCount);
Example 1: In this example, we have an array arr and we want to remove all elements after the first 3 elements. So, we used the splice() method with start index 3 (which is the index of the fourth element) and deleteCount set to the length of the array minus N.
const arr = [1, 2, 3, 4, 5, 6];
const n = 3;
arr.splice(n);
console.log(arr); // Output: [1, 2, 3]
Output
[ 1, 2, 3 ]
Example 2: In this example, we have an array arr and we want to remove all elements after the first 3 elements. So, we used the splice() method with start index 3 (which is the index of the fourth element) and deleteCount set to the length of the array minus N.
const arr = ['apple', 'banana', 'orange', 'grape', 'kiwi'];
const n = 3;
arr.splice(n);
console.log(arr); // Output: ['apple', 'banana', 'orange']
Output
[ 'apple', 'banana', 'orange' ]
How to Get First N Elements from an Array in JavaScript ?
To get the first N elements from an array is a common task in JavaScript. Whether you’re dealing with lists of data, subsets of results, or pagination, this guide will provide you with several efficient methods to achieve this.
Below are the approaches to get the first N number of elements from an array in JavaScript.
Table of Content
- 1. Using the slice() method
- 2. Using a for loop
- 3. Using the splice() method
- 4. Using the filter() method
- 5. Using Lodash _.take() Method
- 6. Using the spread operator
Examples:
Input:
arr = [1, 2, 3, 4, 5, 6], n = 3
Output: [1, 2, 3]
Input:
arr = [6, 1, 4, 9, 3, 5, 7], n = 4
Output: [6, 1, 4, 9]
Contact Us