Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript ES6: Split array into rest and last with destructuring [duplicate]

I just discovered the delightful ES6 destructuring syntax for lists, i.e.

ls = [1, 2, 3]

[first, ...rest] = ls

which sets first to 1 and rest to [2,3]. However, is it possible to split the list into rest=[1,2] and last=3 using similar syntax?

I didn't have any luck googling it. I tried some obvious guesses for such a syntax (see below), but they all produced syntax errors.

[rest..., last] = ls
[...rest, last] = ls

I suppose I could do it by reversing the list twice, so an alternate solution to my question would be a constant time list reversal function.

like image 899
Alex Avatar asked Oct 27 '25 09:10

Alex


1 Answers

What is commonly called "array destructuring" is actually destructuring an iterable, of which an array is a special case. The thing about iterables is that they can be infinite, or "lazy". That is the reason that you cannot destructure into some arbitrary number of elements followed by the last one:

const [...first, last] = integers();

because integers could be

function* integers() {
  let n = 0;
  while (true) yield n++;
}

and then what would last be?


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!