Borislav Hadzhiev
Tue Oct 26 2021·2 min read
Photo by Alex Post
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.
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:
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.
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.
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.
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.