Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring a JavaScript Array by a Variable Index

To my understanding, JavaScript arrays can be destructured according to a specific index by doing the following.

const { 3: selectedByIndex } = arr;

This would assign the value of the element at index 3 to the variable selectedByIndex.

Is there a way to pass in a variable index value to destructure the array? The below does not work, it seems to instead look for the index property on arr.

const index = 3;
const arr = [1, 2, 3, 4, 5]

const { index: selectedByIndex } = arr;
like image 960
shprecure Avatar asked May 18 '26 12:05

shprecure


2 Answers

Yes, you can by setting index inside the square brackets.

const index = 3;
const arr = [1, 2, 3, 4, 5]

const { [index]: selectedByIndex } = arr;

console.log(selectedByIndex)
like image 138
Mina Avatar answered May 20 '26 01:05

Mina


While this works

const a = [1, 2, 3];
const index = 2;

const [,,v1] = a;
// v1 = 3
const { [index]: v2 } = a;
// v2 = 3

The second solution (v2) is a bad design practice, because an array is not an object, but you are accessing it as one.

A better solution would be either

const v3 = a[index]; 
const v4 = a?.[index];

In other words, destructuring is when you know the format of the data structure. If not, JavaScript arrays don't care if you try to get an out-of-bound value, unless the value is not an array, in which case you need optional chaining (e.g. v4).


Edit 2022

To clarify what I meant by the second solution being a "bad design practice", consider this benchmark:

// tested on                      Chrome 105       Firefox 105
let value = list[index];       // fastest, base    fastest, base
let value = list?.[index];     // 2.52% slower     3.74% slower
let { [index]: value } = list; // 47.72% slower    30.76% slower

It's not because a feature exist, and it works, that 1) it's efficient or 2) it's a good design choice. After all, I can certainly hit a nail with a pipe wrench, but there are better tools for the job.


Edit 2024

When the previous edit was added, Array.at was still not generally adopted, however now it is.

const v5 = a.at(index);

This is the preferred way because it is a disambiguation from accessing object properties.

For example:

const i = 1;
const p = 'find';

// old
const v6 = a[i];  // 2
const v7 = a[p];  // 'find() [native code]' (same as a.find)

// new
const v8 = a.at(i);  // 2
const v9 = a.at(p);  // 1 (same as a.at(0)

The new API protects from returning unwanted values by accessing undesired properties.

Bonus: a.at(-2) is the same as a[a.length - 2]

like image 38
Yanick Rochon Avatar answered May 20 '26 01:05

Yanick Rochon



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!