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?
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);
Use object-destructuring
instead:
const splittedArr = [1, 2, 3, 4, 5];
const { 1: second, 4: fifth } = splittedArr;
console.log(second, fifth);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With