9

My airbnb styleguide told me I should use Array Destructuring for the assignment below.

const splittedArr  = [1, 2, 3, 4, 5]
const result = splittedArr[1];

So I wrote it like this using skipping values , to get the second element.

const splittedArr  = [1, 2, 3, 4, 5]
const [, result] = splittedArr;

const splittedArr = [1, 2, 3, 4, 5]
const result = splittedArr[1];

const [, res] = splittedArr;

console.log(result, res);

But for instance when I have a higher indice to destruct

const splittedArr  = [1, 2, 3, 4, 5]
const result = splittedArr[5];

This would mean I have to write it like

const splittedArr  = [1, 2, 3, 4, 5]
const [,,,, result] = splittedArr;

const splittedArr  = [1, 2, 3, 4, 5]

const result = splittedArr[4];

const [, , , , res] = splittedArr;

console.log(result, res);

Question: Is there a better way to write Array Destructuring with skipping values in JavaScript?

Aalexander
  • 4,987
  • 3
  • 11
  • 34
  • That's a guideline not a fixed rule. Have a look at the issues for that part of the guide (e.g. [Why use prefer-destructuring on arrays? #1791](https://github.com/airbnb/javascript/issues/1791)) – Andreas Jan 30 '21 at 10:56
  • 1
    Please use common sense. It's far uglier to do `[,,,,,myvar] = ar` than `const myvar = ar[5]` and any style guide that tells you otherwise is wrong. – 404 Jan 30 '21 at 16:37
  • 1
    Does this answer your question? [Object destructuring solution for long arrays?](https://stackoverflow.com/questions/33397430/object-destructuring-solution-for-long-arrays) – Nguyễn Văn Phong Jan 31 '21 at 04:25
  • My question is about Array Destructuring and not Object destructuring as you can see in my title and the title of your prodivded question. – Aalexander Jan 31 '21 at 07:36

2 Answers2

9

You could treat the array as object and destructure with the index as key and assign to a new variable name.

const
    array = [37, 38, 39, 40, 41, 42, 43],
    { 5: result } = array;

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
5

Use object-destructuring instead:

const splittedArr  = [1, 2, 3, 4, 5];

const { 1: second, 4: fifth } = splittedArr;

console.log(second, fifth);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48