DEV Community

Mohana Naga Venkat Sayempu
Mohana Naga Venkat Sayempu

Posted on • Updated on

Destructuring arrays as objects

Destructuring is one of the widely used feature of ES6. Since arrays are also objects in javascript we can destructure them by using their indices.

let fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];
let { 0:first } = fruits;
console.log(first); // Banana

In above example we are grabbing the first element of the array. Now we will go a little deep and try to grab the first, last and middle elements.

let fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];
let { length, 0:first, [Math.floor(length/2)]:middle, [length-1]: last } = fruits;
console.log(length, first, middle, last); // 5, Banana, Apple, Kiwi

Array have length property, so we grabbing that length and destructuring allows us to use that length right inside. Hence, we are using that length to calculate the middle position.

Happy coding 😃.

Top comments (7)

Collapse
 
jillejr profile image
Kalle Fagerberg

See very little practical use for this but still interesting technique! If I used

let { length, [length-1]: last } = list;

I would just shock all my coworkers and would throw them off, instead of

let length = list.length;
let last = list[length-1];

This technique could really come in handy when need to grab two items out of a list at the same time though. That's a place I'd really consider using it, like with the

let { 0: a, 1: b } = list;
return a > b;

...or whatever. Well got me pondering of how to use it, very interesting. Thanks for sharing! :)

Collapse
 
miketalbot profile image
Mike Talbot ⭐

To be fair you can do that last example as

 let [a,b] = list
 return a > b

Which is way shorter. It would make sense perhaps for getting items from the end of a list, but as you say not very legible.

Collapse
 
jillejr profile image
Kalle Fagerberg

Oh yea forgot about that trick! The most interesting thing about this technique is to find where to use it.

Collapse
 
rsa profile image
Ranieri Althoff

I think you forgot to name middle

Collapse
 
mohananagavenkat profile image
Mohana Naga Venkat Sayempu

Yea, updated the post. Thanks for that 😃

Collapse
 
miketalbot profile image
Mike Talbot ⭐

I can see using this on a sorted list for min, max, median, all the quantiles etc.

Collapse
 
mohananagavenkat profile image
Mohana Naga Venkat Sayempu

Yeah, that would be more realtime example 😃