Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring array get second value?

How to get array using destructing?

const num = [1,2,3,4,5];
const [ first ] = num; //1

console.log(first) I'm able to get 1, but when I try to do const [ null, second ] = num it has expected token error. How to get 2nd item of num array?

like image 217
Alan Jenshen Avatar asked Jun 15 '17 06:06

Alan Jenshen


2 Answers

You can skip parametr name just by putting comma

var num = [1, 2, 3, 4, 5];
var [ ,x] = num;

for more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Ignoring_some_returned_values section Ignoring some returned values

like image 121
Piotr Pasieka Avatar answered Nov 05 '22 09:11

Piotr Pasieka


As alternative you can use object destructuring because arrays are objects:

var {1: second} = num;

But simply omitting the first element as Piotr suggests in their answer is a bit cleaner in this particular case.

See also Object destructuring solution for long arrays?

like image 31
Felix Kling Avatar answered Nov 05 '22 10:11

Felix Kling