How to use the slice() method In Javascript
The slice() method is used to extract a part of an array and returns a new array containing the extracted elements. It does not change the original array. Here, start is the starting index from where to begin extraction and end is the ending index from where to end extraction. The end index is exclusive, i.e., the element at the end index is not included in the extracted array.
Syntax:
array.slice(start, end);
Example 1: In this example, we have an array arr and we want to extract the first 3 elements from it. So, we used the slice() method with a start index of 0 and an end index of 3, which extracts the first 3 elements.
const arr = [1, 2, 3, 4, 5, 6];
const n = 3;
const result = arr.slice(0, n);
console.log(result); // Output: [1, 2, 3]
Output
[ 1, 2, 3 ]
Example 2: In this example, we have an array arr and we want to extract the first 2 elements from it. So, we used the slice() method with a start index of 0 and an end index of 2 to extract the first 2 elements.
const arr = ['apple', 'banana', 'orange', 'grape', 'kiwi'];
const n = 2;
const result = arr.slice(0, n);
console.log(result); // Output: ['apple', 'banana']
Output
[ 'apple', 'banana' ]
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