The Wayback Machine - https://web.archive.org/web/20240828164214/https://www.geeksforgeeks.org/how-to-get-first-n-number-of-elements-from-an-array-in-javascript/
Open In App

How to Get First N Elements from an Array in JavaScript?

Last Updated : 19 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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]

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]

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]

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);

Output
[ 1, 2, 3, 4 ]

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]

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]

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.



Previous Article
Next Article

Similar Reads

How to get all Elements Except First in JavaScript Array?
We will find all the elements in a given array except for the first one using JavaScript. We have a few methods to do this in JavaScript that are described below: Table of Content Using for loopUsing slice() MethodUsing Array.filter methodJavaScript Array.reduce() Method Using shift() MethodUsing Array.from() MethodUsing splice() MethodUsing for lo
5 min read
How to get first N number of elements from an array using ReactJS?
To get the first N number of elements from an array using React JS simply means to display the N number of elements of the array. PrerequisitesReact JSReact Class ComponentApproach to get first N number of elements:We will create an array containing some values using the react class component and from the user input, we will display n number of ele
2 min read
Get the first and last item in an array using JavaScript
JavaScript array is used to store multiple elements in a single variable. It is often used when we want to store a list of elements and access them by a single variable. We will learn how to get the first &amp; last element in an array in JavaScript, along with understanding their implementation through the examples. These are the following approac
5 min read
How to get the elements of one array which are not present in another array using JavaScript?
The task is to get the elements of one array that are not present in another array. Here we are going to use JavaScript to achieve the goal. Here are a few techniques discussed. Approach Take the arrays in variables.Use the .filter() method on the first array and check if the elements of the first array are not present in the second array, Include
2 min read
How to merge the first index of an array with the first index of second array?
The task is to merge the first index of an array with the first index of another array. Suppose, an array is array1 = {a, b, c} and another array is array2 = {c, d, e} if we perform the task on these arrays then the output will be  result array { [0]=&gt; array(2) { [0]=&gt; string(1) "a" [1]=&gt; string(1) "c" } [1]=&gt; array(2) { [0]=&gt; string
4 min read
How to get the first non-null/undefined argument in JavaScript ?
There are many occasions when we get to find out the first non-null or non-undefined argument passed to a function. This is known as coalescing. Approach 1: We can implement coalescing in pre-ES6 JavaScript by looping through the arguments and checking which of the arguments is equal to NULL. We then return the argument that is not NULL immediately
5 min read
How to get the first and last date of current month using JavaScript ?
Given a month and the task is to determine the first and last day of that month in proper format using JavaScript. JavaScript getDate() Method: This method returns the day of the month (from 1 to 31) for the defined date. Syntax: Date.getDate() Parameters: This method does not accept any parameters. Return value: It returns a number from 1 to 31, r
3 min read
How to get the first day of the year in JavaScript ?
Given a date/year and the task is to get the first day of the year using JavaScript. Approach 1: Use getFullYear() Method to get the year from the given date.Use the new Date() function to create the new date object using year, month, and day. Example: This example uses the getFullYear() method to get the full year of the current day and then get t
1 min read
How to get the first key name of a JavaScript object ?
Given an object and the task is to get the first key of a JavaScript Object. Since a JavaScript object does not contains numbered index so we use the following approaches to get the first key name of the object. Approach 1: First take the JavaScript Object in a variable.Use object.keys(objectName) method to get access to all the keys of object.Now,
3 min read
How to get the first three characters of a string using JavaScript ?
In this article, we are going to learn how to get the first three characters of a string using JavaScript. Example: Input: todayOutput: todInput: tomorrowOutput: tomThese are the approaches by which we can get the first three characters of a string using JavaScript: Table of Content Approach 1: Using Slice() methodApproach 2: Using string.substr()
3 min read
JavaScript Program to Swap First and Last Elements in an Array
In this article, we are going to learn about swaping the first and last elements in an array in JavaScript. Swaping the first and last elements in a JavaScript array refers to swapping their positions, effectively exchanging the values at these two distinct indices within the array. There are several methods that can be used to interchange the firs
4 min read
How to get n largest elements from array in JavaScript ?
Here in this article, we will see how we can find the n maximum element from the array using Javascript. Example: Input: arr = [1, 2, 3, 4, 5, 6], n = 3;Output: 4, 5, 6Explanation: Here we will see the 3 largest elements in the given array are 4, 5, 6. Input: arr = [5, 76, 32, 98, 52, 57] n = 2;Output: 98 , 76 There are some common ways to find the
3 min read
How to get removed elements of a given array until the passed function returns true in JavaScript ?
The arrays in JavaScript have many methods which make many operations easy. In this article let us see different ways how to get the removed elements before the passed function returns something. Let us take a sorted array and the task is to remove all the elements less than the limiter value passed to the function, we need to print all the removed
4 min read
How to create an array of elements, ungrouping the elements in an array produced by zip in JavaScript ?
We can create an array of elements by ungrouping the elements in an array produced by zip by using different methods in JavaScript such as Math.max(), array specific methods namely Array.prototype.map(), Array.prototype.reduce() and Array.prototype.forEach(). This operation can also be termed as unzip. Before looking at unzip, let us understand wha
2 min read
Javascript Program to Interchange elements of first and last rows in matrix
Given a 4 x 4 matrix, we have to interchange the elements of first and last row and show the resulting matrix.Examples : Input : 3 4 5 0 2 6 1 2 2 7 1 2 2 1 1 2 Output : 2 1 1 2 2 6 1 2 2 7 1 2 3 4 5 0 Input : 9 7 5 1 2 3 4 1 5 6 6 5 1 2 3 1 Output : 1 2 3 1 2 3 4 1 5 6 6 5 9 7 5 1 The approach is very simple, we can simply swap the elements of fir
2 min read
JavaScript Program to Interchange Elements of First & Last in a Matrix Across Columns
We are given a matrix and we have to interchange the elements of the first and last columns with each other in a matrix. Example: Input 1 : 1 1 5 0 2 3 7 2 8 9 1 3 6 7 8 2Output 1 : 0 1 5 1 2 3 7 2 3 9 1 8 2 7 8 6Table of Content Using the swapping logicUsing forEach methodUsing the swapping logicIn this method, we Iterate through each column of th
3 min read
How to get all ID of the DOM elements with JavaScript ?
Given a HTML document and the task is to get the all ID of the DOM elements in an array. There are two methods to solve this problem which are discusses below: Approach 1: First select all elements using $('*') selector, which selects every element of the document.Use .each() method to traverse all elements and check if it has an ID.If it has an ID
2 min read
Moment.js Customize First Day of Week and First Week of Year
Moment.js is a JavaScript date library for parsing, validating, manipulating, and formatting dates. In the calendar, we can use Moment.js to customize the First Day of the Week and the First Week of the Year as per our requirements. We will be using the moment.updateLocale() method for this customization. Syntax: moment.updateLocale('en', { week :
2 min read
Difference between :first-child and :first-of-type selector in CSS
The :first-child and :first-of-type selectors in CSS are used to target specific child elements within a parent. The :first-child selector targets an element if it is the first child of its parent, regardless of type. On the other hand, the :first-of-type selector targets the first occurrence of a specified element type within its parent. Understan
2 min read
How to remove specific elements from the left of a given array of elements using JavaScript ?
In this article, we will learn How to remove specific elements from the left of a given array of elements using JavaScript. We have given an array of elements, and we have to remove specific elements from the left of a given array. Here are some common approaches: Table of Content Using splice() methodUsing shift MethodApproach: Using splice() meth
2 min read
How to get total number of elements used in array in PHP ?
In this article, we will discuss how to get total number of elements in PHP from an array. We can get total number of elements in an array by using count() and sizeof() functions. Using count() Function: The count() function is used to get the total number of elements in an array. Syntax: count(array) Parameters: It accepts a single parameter i.e.
2 min read
How to get elements in reverse order of an array in PHP ?
An array is a collection of elements stored together. Every element in an array belong to a similar data type. The elements in the array are recognized by their index values. The elements can be subjected to a variety of operations, including reversal. There are various ways to reverse the elements of an array : Table of Content Using for LoopUsing
4 min read
Javascript Program to Split the array and add the first part to the end | Set 2
Given an array and split it from a specified position, and move the first part of array add to the end.   Examples:   Input : arr[] = {12, 10, 5, 6, 52, 36} k = 2 Output : arr[] = {5, 6, 52, 36, 12, 10} Explanation : Split from index 2 and first part {12, 10} add to the end . Input : arr[] = {3, 1, 2} k = 1 Output : arr[] = {1, 2, 3} Explanation :
2 min read
JavaScript Program to Find the First Non-Repeated Element in an Array
Finding the first non-repeated element in an array refers to identifying the initial occurrence of an element that does not occur again elsewhere within the array, indicating uniqueness among the elements. Examples: Input: {-1, 2, -1, 3, 0}Output: 2Explanation: The first number that does not repeat is : 2Input: {9, 4, 9, 6, 7, 4}Output: 6Explanatio
5 min read
JavaScript Program to Find Index of First Occurrence of Target Element in Sorted Array
In this article, we will see the JavaScript program to get the first occurrence of a number in a sorted array. We have the following methods to get the first occurrence of a given number in the sorted array. Methods to Find the Index of the First Occurrence of the element in the sorted arrayTable of Content Methods to Find the Index of the First Oc
6 min read
How to Remove First and Last Element from Array using JavaScript?
Removing the first and last elements from an array is a common operation. This can be useful in various scenarios, such as data processing, filtering, or manipulation. Example: Input: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]Output: [ 2, 3, 4, 5, 6, 7, 8, 9 ]Removing first and last element in array can be done using below approaches: Table of Content Using
2 min read
Delete the first element of array without using shift() method in JavaScript
Given an array containing some array elements and the task is to remove the first element from the array and thus reduce the size by 1. We are going to perform shift() method operation without actually using it with the help of JavaScript. There are two approaches that are discussed below: Table of Content Method 1: Using splice() MethodMethod 2: U
2 min read
How to get array structure with alert() in JavaScript?
Here is the code to see the array structure using alert() . Here below few techniques are discussed Approach 1: First take the values in a variable(lets arr). Pass the array name in the alert() . We can directly use the array name because arrayName automatically converted to arrayName.toString() Example 1: This example follows the approach discusse
2 min read
How to get the index of the function in an array of functions which executed the fastest in JavaScript ?
In this example, we will learn how to get the index of the function in an array of functions that is executed the fastest in JavaScript. Example: Input: fun[] = [ hello, hello1, hello2 ] Output: index of fastest is 0. Explanation: Function hello execute fastest in all functions. Input: fun[] = [ while1, while2, while3 ] Output: index of fastest fun
4 min read
How to get an array of function property names from own enumerable properties of an object in JavaScript ?
Enumerable Properties: All the properties of an object that can be iterated using for..in loop or Object.keys() method are known as enumerable properties. In this article, we will see how to get an array of functions of an object that are enumerable. It can be achieved by following these 2 steps. Using Object.keys() method, we can get an array of a
2 min read