javascriptarraysdestructuringairbnb-js-styleguide

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?


Solution

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