Get the first N elements from an Array in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 05 20211 min read

banner

Photo by Blake Weyland

Get the first N elements from an Array #

To get the first N elements from an Array, call the slice method on the array, passing in 0 as the first parameter and the number of elements to get as the second, e.g. arr.slice(0, 3) returns a new array with the first 3 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 array).

The first parameter we pass to the Array.slice method is the start index, the second is the end index (up to this index, but not including).

Even if the end index you provide to the Array.slice method exceeds the array's length, the method does not throw an error, but returns all array elements.
index.js
const arr = ['a', 'b', 'c']; const first100 = arr.slice(0, 100); console.log(first100); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c']

In the example we've 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee