How to use the filter() method In Javascript
We can also use the filter() method but this method is not much efficient because it iterates over the entire array.
Example: In this example, we have used filter() method.
const arr = [1,2,3,4,5,6];
const n = 4;
const newArray = arr.filter((element, index) => index < n);
console.log(newArray);
Output:
[ 1, 2, 3, 4 ]
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]