Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
19
rated 0 times [  21] [ 2]  / answers: 1 / hits: 57539  / 7 Years ago, tue, june 13, 2017, 12:00:00

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


More From » arrays

 Answers
27

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)




[#57473] Sunday, June 11, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
benitoh

Total Points: 150
Total Questions: 113
Total Answers: 104

Location: India
Member since Wed, Aug 26, 2020
4 Years ago
benitoh questions
Sun, Mar 21, 21, 00:00, 3 Years ago
Mon, May 13, 19, 00:00, 5 Years ago
;