Search code examples
javascriptarraysecmascript-6destructuring

How can I get last element of an array by using Destructuring


I am learning ES6 Destructuring

I am getting an error Rest element must be last element

Here is what I have right now

const siblings = ['John','Jack','Amanda','Allie','Bob']

let [firstSiblingName,...middleAllSiblingsName,lastSiblingName] = siblings
console.log(lastSiblingName)

What I want is

firstSiblingName = 'John'
middleAllSiblingsName = ['Jack','Amanda','Allie']
lastSiblingName = 'Bob'

If I remove lastSiblingName then it works, but in that way I cannot get last element separately.

What I am doing wrong , and how can I make it to achieve the required output.


Solution

  • You can't, not with rest syntax alone - rest will always consume all of the rest of the elements of the array. You'll have to .pop() the last element instead, after extracting the middle elements:

    const siblings = ['John','Jack','Amanda','Allie','Bob'];
    
    let [firstSiblingName,...middleAllSiblingsName] = siblings;
    const lastSiblingName = middleAllSiblingsName.pop();
    console.log(lastSiblingName)