Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Destructuring Skipping Values

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?

like image 460
Aalexander Avatar asked Jan 30 '21 10:01

Aalexander


2 Answers

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);
like image 88
Nina Scholz Avatar answered Sep 24 '22 21:09

Nina Scholz


Use object-destructuring instead:

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

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

console.log(second, fifth);
like image 36
Majed Badawi Avatar answered Sep 23 '22 21:09

Majed Badawi