Get first and last elements in array, ES6 way

53,213

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)
Share:
53,213
Nicholas
Author by

Nicholas

Updated on April 04, 2020

Comments

  • Nicholas
    Nicholas about 4 years

    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

  • loganfsmyth
    loganfsmyth almost 7 years
    It's a rest not a spread FYI, and it's not an operator, it's just syntax.
  • Bergi
    Bergi almost 7 years
    Uh, yeah, but don't do that. let a = array[0], b = array[array.length-1]; is just so much cleaner. If we really wanted to make it as concise as possible, there's also let {0:a, length:l, [l-1]:b} = array;
  • Pranav C Balan
    Pranav C Balan almost 7 years
    @bergi is l get defined just before assigning value into b???
  • Bergi
    Bergi almost 7 years
    Yes, it's evaluated strictly left-to-right
  • Pranav C Balan
    Pranav C Balan almost 7 years
    @bergi thanks, now it's clear to me :)
  • codeBelt
    codeBelt over 2 years
    const { 0: first, [array.length - 1]: last, ...middle } = array; ____________________________________________________________‌​____________ console.log(first, Object.values(middle), last);