Get the First 2 Elements of an Array in Javascript

avatar

Borislav Hadzhiev

Tue Oct 26 20212 min read

banner

Photo by Alex Post

Get the First 2 Elements of an Array #

To get the first 2 elements of an array, call the slice method passing it a start index of 0 and an end index of 2 as parameters. The slice method will return a new array containing the first 2 elements of the original array.

index.js
const arr = ['apple', 'orange', 'banana', 'kiwi']; const first2 = arr.slice(0, 2); console.log(first2); // ๐Ÿ‘‰๏ธ ['apple', 'orange']

We used the Array.slice method to get the first 2 elements of an array.

We passed the following arguments to the slice method:

  1. start index - the index of the first element that should be included in the new array.
  2. end index - go up to, but not including this index when extracting elements.
Indexes are zero-based in JavaScript, meaning the index of the first element in an array is 0, and the last - array.length - 1.

By specifying a start index of 0 and an end index of 2, we get a new array containing the elements at positions 0 and 1, in other words the first 2 elements.

Note that the slice method does not change the contents of the original array, it returns a new array.

An alternative approach is to use destructuring assignment.

index.js
const arr = ['apple', 'orange', 'banana', 'kiwi']; const [first, second] = arr; console.log(first); // ๐Ÿ‘‰๏ธ 'apple' console.log(second); // ๐Ÿ‘‰๏ธ 'orange'

In this example we used destructuring assignment to pull out the values of the first and second array elements and assigned them to the first and second variables.

When using destructuring, the order of variable declaration and array elements is preserved. It goes from left (element at index 0) to right (index 1), etc.

We are basically pulling the values from the elements in the array and assigning them to variables.

You could also skip an element when using this approach.

index.js
const arr = ['apple', 'orange', 'banana', 'kiwi']; const [, second, third] = arr; console.log(second); // ๐Ÿ‘‰๏ธ 'orange' console.log(third); // ๐Ÿ‘‰๏ธ 'banana'

We used a comma to skip the array element at index 0, so we can get the values of the second and third array elements.

Further Reading #

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