JavaScript - Get first and last Item of JS Array
These are the following ways to get first and last element of the given array:
1. Using length Property
The array length property in JavaScript is used to set or return the number of elements in an array.
let arr = [3, 2, 3, 4, 5];
let f = arr[0];
let l = arr[arr.length - 1];
console.log(f, l)
Output
3 5
2. Using Array.pop() and Array.shift() Method
The Array.pop() method removes the last element of the array and returns it and the Array.shift() method removes the first element from the array and returns it.
let arr = [3, 2, 3, 4, 5];
let f = arr.shift(0);
let l = arr.pop();
console.log(f, l)
Output
3 5
3. Using Array.slice() Method
The Array.slice() method returns the part of the array by slicing it with provided index and length.
let arr = [3, 2, 3, 4, 5];
let f = arr.slice(0, 1);
let l = arr.slice(-1);
console.log(f, l)
Output
[ 3 ] [ 5 ]
4. Using Array.filter() Method
The Array.filter() method returns a filtered array that removes the element which returns false for the callback function.
let arr = [3, 2, 3, 4, 5];
let [f, l] = arr.filter((item, i) =>
(i == 0) || (i == arr.length - 1));
console.log(f, l)
Output
3 5
5. Using Spread Operator
The Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 value is expected. It allows us the privilege to obtain a list of parameters from an array.
const arr = [1, 2, 3, 4, 5];
const [f, ...rest] = arr;
const l = rest.pop();
console.log(f, l)
Output
1 5
6. Using Array.at() Method
The Array.at() method in JavaScript allows to access elements of an array by their index. To get the first and last elements of an array using the at() method, pass the desired indices to the method. The first element has an index of 0. Array last element can be accessed by using the array's length-1 as the index.
const arr = [1, 2, 3, 4, 5];
let f = arr.at(0);
let l = arr.at(arr.length - 1);
console.log(f, l)
Output
1 5