Array Destructuring Skipping Values

1.1k Views Asked by At

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?

2

There are 2 best solutions below

0
Nina Scholz On BEST ANSWER

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);

0
Majed Badawi On

Use object-destructuring instead:

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

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

console.log(second, fifth);