6

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;
shprecure
  • 61
  • 3

3 Answers3

6

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)
Mina
  • 14,386
  • 3
  • 13
  • 26
2

The same way you pass a variable key when creating an object -- put it in [].

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

const { [index]: selectedByIndex } = arr;
console.log(selectedByIndex);

But unless this is just a part of a more complex destructuring pattern, arr[index] is obviously simpler.

Barmar
  • 741,623
  • 53
  • 500
  • 612
2

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

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.

Yanick Rochon
  • 51,409
  • 25
  • 133
  • 214
  • `"The second solution (v2) is a bad design practice, because an array is not an object..."`. I don't think that is a bad practice. `Arrays` in JavaScript are `Objects` like almost everything in JavaScript. – Xion 14 Sep 28 '22 at 19:56
  • @Xion14 please, read my edit. – Yanick Rochon Sep 28 '22 at 23:35