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:
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]
Using the slice() method
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.
JavaScript
const arr = [1, 2, 3, 4, 5, 6];
const n = 3;
const result = arr.slice(0, n);
console.log(result); // 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.
JavaScript
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' ]
Using a for loop
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.
JavaScript
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]
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.
JavaScript
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' ]
Using the splice() method
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.
JavaScript
const arr = [1, 2, 3, 4, 5, 6];
const n = 3;
arr.splice(n);
console.log(arr); // 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.
JavaScript
const arr = ['apple', 'banana', 'orange', 'grape', 'kiwi'];
const n = 3;
arr.splice(n);
console.log(arr); // Output: ['apple', 'banana', 'orange']
Output[ 'apple', 'banana', 'orange' ]
Using the filter() method
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.
JavaScript
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 ]
Using Lodash _.take() Method
Lodash _.take() method is used to create a slice of an array with n elements from the beginning.
Syntax:
_.take(array, n);
Example: In this example, we are creating a new array having 5 elements of an old array by the use of the lodash _.take() method.
JavaScript
const _ = require('lodash');
let x = [1, 2, 3, 4, 5, 6, 7]
let newArray = _.take(x, 5);
console.log(newArray);
Output:
[ 1, 2, 3, 4, 5 ]
Using the spread operator
Another approach to get the first N number of elements from an array in JavaScript is by using the spread operator along with array destructuring. This method creates a shallow copy of the original array with the specified number of elements.
Syntax:
const newArray = [...array.slice(0, n)];
Example:
JavaScript
const arr = [1, 2, 3, 4, 5, 6];
const n = 4;
const newArray = [...arr.slice(0, n)];
console.log(newArray);
Using the reduce() method
The reduce() method executes a reducer function on each element of the array, resulting in a single output value. We can use it to accumulate the first N elements into a new array.
Example: In this example, we use the reduce() method to accumulate the first N elements into a new array. The reducer function checks the index and, if it is less than N, adds the current element to the accumulator.
JavaScript
const arr = [1, 2, 3, 4, 5, 6];
const n = 3;
const result = arr.reduce((acc, curr, index) => {
if (index < n) {
acc.push(curr);
}
return acc;
}, []);
console.log(result); // Output: [1, 2, 3]
Using Array.from()
The Array.from() method creates a new, shallow-copied array instance from an array-like or iterable object. By combining it with Array.prototype.keys(), we can easily extract the first N elements from an array
Example: This approach is concise and leverages modern JavaScript methods (Array.from(), .keys(), .slice(), and .map()) to achieve the desired outcome efficiently. It ensures that the original array remains unmodified while providing a clean way to extract a subset of its elements.
JavaScript
const arr = [1, 2, 3, 4, 5, 6];
const n = 3;
const result = Array.from(arr.keys()).slice(0, n).map(index => arr[index]);
console.log(result); // Output: [1, 2, 3]
Getting the first N elements from an array can be done using various methods in JavaScript. Whether you prefer built-in methods like slice() or third-party libraries like Lodash, each approach offers unique benefits. Understanding these methods enhances your ability to handle arrays effectively in different scenarios.
Please Login to comment...