JavaScript - How to Get First N Elements from an Array?
Last Updated :
26 Nov, 2024
There are different ways to get the first N elements from 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]
1. Using 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);
JavaScript
const arr = [1, 2, 3, 4, 5, 6];
const n = 3;
const result = arr.slice(0, n);
console.log(result);
2. Using for Loop
We can also use a for loop to iterate through the array and extract the first N elements. we will iterate the loop by N number that we want and we will use console.log to print those numbers into the console.
Syntax
for (let i = 0; i < n; i++) {
// Access and store elements here
}
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]
3. Using 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);
JavaScript
const arr = [1, 2, 3, 4, 5, 6];
const n = 3;
arr.splice(n);
console.log(arr); // Output: [1, 2, 3]
4. Using filter() Method
We can also use the filter() method but this method is not much efficient because it iterates over the entire array.
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 ]
5. 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);
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 ]
6. Using 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)];
JavaScript
const arr = [1, 2, 3, 4, 5, 6];
const n = 4;
const newArray = [...arr.slice(0, n)];
console.log(newArray);
7. Using 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.
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);
8. Using Array.from() Method
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
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);
Similar Reads
JavaScript - Find Index of a Value in Array Here are some effective methods to find the array index with a value in JavaScript.Using indexOf() - Most Used indexOf() returns the first index of a specified value in an array, or -1 if the value is not found. JavaScriptconst a = [10, 20, 30, 40, 50]; // Find index of value 30 const index = a.inde
2 min read
JavaScript - How to Get First N Elements from an Array? There are different ways to get the first N elements from 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 = 4Output: [6, 1, 4, 9]1. Using slice() MethodThe slice() method is used to extract a part of an array and returns a new
4 min read
How to Copy Array by Value in JavaScript ? There are various methods to copy array by value in JavaScript.1. Using Spread OperatorThe JavaScript spread operator is a concise and easy metho to copy an array by value. The spread operator allows you to expand an array into individual elements, which can then be used to create a new array.Syntax
4 min read
What is the most efficient way to concatenate N arrays in JavaScript ? In this article, we will see how to concatenate N arrays in JavaScript. The efficient way to concatenate N arrays can depend on the number of arrays and the size of arrays. To concatenate N arrays, we use the following methods:Table of ContentMethod 1: Using push() MethodMethod 2: Using concat() Met
3 min read
How to Merge Two Arrays and Remove Duplicate Items in JavaScript? Given two arrays, the task is to merge both arrays and remove duplicate items from merged array in JavaScript. The basic method to merge two arrays without duplicate items is using spread operator and the set constructor.1. Using Spread Operator and Set() ConstructorThe Spread Operator is used to me
3 min read
How to clone an array in JavaScript ? In JavaScript, cloning an array means creating a new array with the same elements as the original array without modifying the original array.Here are some common use cases for cloning an array:Table of ContentUsing the Array.slice() MethodUsing the spread OperatorUsing the Array.from() MethodUsing t
6 min read
JavaScript - Check if JS Array Includes a Value? To check if an array includes a value we can use JavaScript Array.includes() method. This method returns a boolean value, if the element exists it returns true else it returns false.1. Using Array.includes() Method - Mostly Used The JS array.includes() method returns true if the array contains the s
4 min read
JavaScript - Create an Object From Two Arrays Here are the different methods to create an object from two arrays in JavaScript1. Using for-each loopThe arr.forEach() method calls the provided function once for each element of the array. JavaScriptconst a1 = ['name', 'age', 'city']; const a2 = ['Ajay', 25, 'New Delhi']; const res = {}; a1.forEac
3 min read
How to remove falsy values from an array in JavaScript ? Falsy/Falsey Values: In JavaScript, there are 7 falsy values, which are given below falsezero(0,-0)empty string("", ' ' , ` `)BigIntZero(0n,0x0n)nullundefinedNaNIn JavaScript, the array accepts all types of falsy values. Let's see some approaches on how we can remove falsy values from an array in Ja
6 min read
JavaScript - Use Arrays to Swap Variables Here are the different methods to swap variables using arrays in JavaScript1. Using Array DestructuringArray destructuring is the most efficient and modern way to swap variables in JavaScript. This method eliminates the need for a temporary variable.JavaScriptlet x = 5; let y = 10; [x, y] = [y, x];
3 min read