Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first and last elements in array, ES6 way [duplicate]

let array = [1,2,3,4,5,6,7,8,9,0]

Documentation is something like this

[first, ...rest] = array will output 1 and the rest of array

Now is there a way to take only the first and the last element 1 & 0 with Destructuring

ex: [first, ...middle, last] = array

I know how to take the first and last elements the other way but I was wondering if it is possible with es6

like image 761
Nicholas Avatar asked Jun 13 '17 17:06

Nicholas


People also ask

How do I find the first and last elements of an array?

To get the first and last elements of an array, access the array at index 0 and the last index. For example, arr[0] returns the first element, whereas arr[arr. length - 1] returns the last element of the array.

How do I find the last 3 elements of an array?

To get the last N elements of an array, call the slice method on the array, passing in -n as a parameter, e.g. arr. slice(-3) returns a new array containing the last 3 elements of the original array. Copied!

How do you find the last two elements of an array?

To access the last n elements of an array, we can use the built-in slice() method by passing -n as an argument to it. n is the number of elements, - is used to access the elements at end of an array.


1 Answers

The rest parameter can only use at the end not anywhere else in the destructuring so it won't work as you expected.

Instead, you can destructor certain properties(an array is also an object in JS), for example, 0 for first and index of the last element for last.

let array = [1,2,3,4,5,6,7,8,9,0]

let {0 : a ,[array.length - 1] : b} = array;
console.log(a, b)

Or its better way to extract length as an another variable and get last value based on that ( suggested by @Bergi) , it would work even there is no variable which refers the array.

let {0 : a ,length : l, [l - 1] : b} = [1,2,3,4,5,6,7,8,9,0];
console.log(a, b)
like image 107
Pranav C Balan Avatar answered Oct 18 '22 19:10

Pranav C Balan