_kud's tech blog

How to get the last item of an array with destructuring

Today, we'll see a little trick to get the last item of an array with destructuring.

As you may already know, destructuring is a way to unpack values from an array. It is really useful to create some variables really quickly.

So let's say we've got an array of numbers like that:

1const arr = [10, 20, 30, 40, 50]

destructuring

In this array, we want the first element that we'll call a, so this is where destructuring will be useful:

1const [a] = [10, 20, 30, 40, 50]

As you can imagine, a will return 10.

rest?

Now, we want to take the first one, the second one, but also the rest.

1const [a, b, ...rest] = [10, 20, 30, 40, 50]

In this way, you'll get those return values:

1const [a, b, ...rest] = [10, 20, 30, 40, 50]
2
3console.log(a) // 10
4console.log(b) // 20
5console.log(rest) // [30, 40, 50]

(By the way, rest can be called as you prefer as long as you use ... before).

slice

Now, and this is the trick of this post, we want the last item of this array. In other way, we want a variable with the value 50.

For that, we'll use slice(-1).

1const [a] = [10, 20, 30, 40, 50].slice(-1)
2
3console.log(a) // 50

A little note, be careful with this way because using slice(-1) only keeps the last item, so:

1const [a, ...rest] = [10, 20, 30, 40, 50].slice(-1)
2
3console.log(a) // 50
4console.log(rest) // []

reverse

Another way could be to use reverse() like:

1const [a, ...rest] = [10, 20, 30, 40, 50].reverse()
2
3console.log(a) // 50
4console.log(rest) // [40, 30, 20, 10]

💡 idea

The reason of this post is that I was a bit surprised at first not to be able to do:

1const [a, ...rest, z] = [10, 20, 30, 40, 50]
2
3console.log(a) // 10
4console.log(rest) // [20, 30, 40]
5console.log(z) // [50]

It sounded logical to me. I'd be interested of your point of view about this.


Hope you enjoyed the reading and you'll get fun with destructuring, it is really powerful. Bye!