How to use a for loop In Javascript
We can also use a for loop to iterate through the array and extract the first N elements.
Syntax:
for (let i = 0; i < n; i++) {
// Access and store elements here
}
Example 1: In this example, we have initialized an empty array result and used a for loop to iterate through the first n elements of the original array arr. We accessed and stored the elements in the result array.
const arr = [1, 2, 3, 4, 5, 6];
const n = 3; // Number of elements to extract
const result = [];
for (let i = 0; i < n; i++) {
result.push(arr[i]);
}
console.log(result); // Output: [1, 2, 3]
Output
[ 1, 2, 3 ]
Example 2: In this example, we declare an empty array result to store the extracted elements. Then, we use a for loop to iterate over the elements of the original array arr and push the first n elements to the result array using the push() method. The loop condition is set to terminate when either n elements have been extracted or all the elements of the original array have been processed.
const arr = ['apple', 'banana', 'orange', 'grape', 'kiwi'];
const n = 3;
const result = [];
for (let i = 0; i < n && i < arr.length; i++) {
result.push(arr[i]);
}
console.log(result); // 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