How to access the last element of an array using destructuring?

Viewed 111

Suppose I have an array like this: [2, 4, 6, 8, 10].

I want to access the first and last element of this array using destructuring, currently I'm doing this:

const array = [2, 4, 6, 8, 10];
const [first, , , , last] = array;
console.log(first, last);

But this is only works with arrays of length 5 and is not generic enough.

In Python I could do something like this:

array = [2, 4, 6, 8, 10]
first, *mid, last = array
print(first, last)

But in JS this is not possible since rest elements should be the last. So, is there some way to do this in JS or this is not possible?

3 Answers

You can use object destructuring and grab the 0 key (which is the first element) and rename it to first & then using computed property names you can grab the array.length - 1 key (which is the last element) and rename it to last.

const array = [2, 4, 6, 8, 10];
const { 0: first, [array.length - 1]: last } = array;
console.log(first, last);

You can also grab the length via destructuring and then use that to grab the last element.

const array = [2, 4, 6, 8, 10];
const { length, 0: first, [length - 1]: last } = array;
console.log(first, last);

Another simple approach to access the last element would be to use the Array.prototype.at method. This is not related to destructuring but it's worth knowing.

const array = [2, 4, 6, 8, 10];
console.log(array.at(-1));

Not necessarily using destructuring, but still concise in my opinion:

const arr = [1, 2, 3, 4, 5];
const [ first, last ] = [ arr.at(0), arr.at(-1) ];

console.log(first, last);

No, you can't use destructuring like that without convoluted workarounds.
A shorter, more readable alternative is to just pop:

const array = [2, 4, 6, 8, 10];
const [first, ...middle] = array;
const last = middle.pop();

console.log(first, middle, last);

Or, just access them by index:

const array = [2, 4, 6, 8, 10];
const first = array[0];
const last = array[array.length - 1];

console.log(first, last);

Related