Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making ...rest item first while assigning value by array destructuring [duplicate]

I know that

var a = [12,23,132,12,3];
var [first, ...rest] = a;

will give first = 12 and rest = [23,132,12,3]

What I would like to do is make rest as the first variable. Something like this

var a = [12,23,132,12,3];
var [...rest, last] = a;

which should give me rest = [12,23,132,12] and last = 3

But this is a wrong syntax and I will get an error that will say

SyntaxError: Rest element must be last element

I know that I can achieve this by reversing the array and then destructuring like this

var a = [12,23,132,12,3];
var [last, secondLast, ...rest] = a.reverse();

which will give me last = 3, secondLast = 12 and rest = [132,23,12] and then I would again have to reverse() the rest.

I can also use indexes and directly access the array elements as well. But that is not desired.

My question is, are there any other ways to achieve what I am trying to do (using rest operators ?) ?

like image 209
Prasanna Avatar asked May 19 '26 22:05

Prasanna


2 Answers

You can use Destructuring assignment along with Array#pop() method to get the last element, and the rest in your variables:

let [last, ...rest] = [a.pop(), ...a];

You can test the results here and see that pop() is the fastest solution among other ones.

Note:

If we want to keep the original array intact, we just need to add the removed item

a.push(last);
  • The .pop() call will get the last element from the array and affects the original array so there's only the rest of it. That fits exactly your needs.
  • We used a.push(last); to retrieve the initial state of a array, this will avoid cloning the array or having an additional variable to clone the a array.

Demo:

var a = [12, 23, 132, 12, 3];

let [last, ...rest] = [a.pop(), ...a];

a.push(last);

console.log(last);
console.log(rest);
console.log(a);
like image 143
cнŝdk Avatar answered May 21 '26 11:05

cнŝdk


You can use array.slice with negative indexes...

const [others, last] = [a.slice(0,-1), ...a.slice(-1)]
like image 25
Martin Stone Avatar answered May 21 '26 11:05

Martin Stone



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!