Get the first N elements of an Array in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Get the first N elements of an Array #

Use the Array.slice() method to get the first N elements of an array, e.g. const first3 = arr.slice(0, 3). The slice() method will return a new array containing the first N elements of the original array.

index.js
const arr = ['a', 'b', 'c', 'd', 'e', 'f']; const first3 = arr.slice(0, 3); // 👉️ ['a', 'b', 'c'] console.log(first3); const first2 = arr.slice(0, 2); // 👉️ ['a', 'b'] console.log(first2);

The Array.slice method does not modify the original array.

Instead, it creates a new array (a shallow copy of the original).

The arguments we passed to the Array.slice method are:

  1. start index - the index of the first element to be included in the new array.
  2. end index - extract elements up to, but not including this index.

For our purposes, we provide a start index of 0 to start extracting elements from the start of the array.

When the start index is 0, you can think of the end index as the number of elements the new array should contain.

For example, arr.slice(0, 3) returns a new array containing the first 3 elements of the original array (array elements at index 0, 1 and 2).

Even if the end index you provide to the Array.slice method exceeds the array's length, the method does not throw an error, instead it returns all array elements.
index.js
const arr = ['a', 'b', 'c']; const first100 = arr.slice(0, 100); console.log(first100); // 👉️ ['a', 'b', 'c']

We tried to get the first 100 elements of an array, which only contains 3 elements.

As a result, the new array contains all 3 elements of the original array.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.