How to get first N elements of an Array in JavaScript?

In this tutorial we will go through how to get the first N elements of an Array in JavaScript. There are several ways to achieve this. In this blog we will look at two most efficient ways to do this task.

One is the slice() method and second one filter() method. Let’s see at each of them one by one.

slice() method

The slice() function is used to obtain the top n elements from an array. It’s the most convenient way to obtain things. The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (where end is not included). In this the start and end represents the index of items in the given array. The original array will not be modified.

Code:

const arr = [11, 12, 13, 14, 15, 16, 17, 18, 19, 110];

// get the first 5 elements
const n = 5;

const newArr = arr.slice(0, n);
console.log(newArr);
// [11, 12, 13, 14, 15]

filter() method

To filter the first n records from the array, we’ll need to use the filter the elements by index.

Code:

const arr = [11, 12, 13, 14, 15, 16, 17, 18, 19, 110];

// get the first 5 elements
const n = 5;

const newArr = arr.filter((x, i) => i < n);
console.log(newArr);
// [11, 12, 13, 14, 15]

Hope you have understood the syntax and the code used above. Comment below in case you have any doubts.

Leave a Comment