Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 array destructuring for specific index [duplicate]

I have an Array const arr = new Array(100).

And I set

arr[0] = 'A'
arr[49] = 'X'

When destructuring the 1st element, I can do it like:

let [first] = arr

How the statement would be like if I want to access to the 50th element by destructuring expression?

like image 306
LiuWenbin_NO. Avatar asked May 17 '19 08:05

LiuWenbin_NO.


People also ask

How do you Destructure an array inside an array?

Destructuring in Arrays. To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element. const [var1, var2, ...]

How do you Destructure the first element of an array?

Destructuring takes each variable on the array on the left-hand side and maps it to the element at the same index in the animals array. When we write out firstElement , we are saying we want to get access to the first element in the animals array and assign it to the variable of firstElement.

What is Destructure in es6?

Destructuring means to break down a complex structure into simpler parts. With the syntax of destructuring, you can extract smaller fragments from objects and arrays. It can be used for assignments and declaration of a variable.

How do you Destructure a multidimensional array?

Similarly, to destructure arrays to multiple variables, use the square brackets [ ] instead of curly brackets. Arrays: const [variable1,variable2] = arrayName; Note: In the case of destructuring objects, the name of the variables should be the same as the name of the properties of the object.


1 Answers

You can grab the element using object destructuring, like so:

const arr = Array(50).fill(0).map((_, i) => `Element ${i + 1}`)

const {49: fifty} = arr
console.log(fifty)
like image 179
Kobe Avatar answered Oct 10 '22 02:10

Kobe