-2

Pretty much everything is in the title but i'll give you an example :

// i can't know the content of this string but for the exemple she's here
let str = 'elem-0, elem-1, elem-2, elem-3';

// how to properly write this line because this line is not write in an array 'destructuring way'
let array = str.split(',')[0];

// return me : "elem-0" (and he has to)
console.log(array);
2
  • 1
    let [array] = str.split(','); Commented Dec 27, 2018 at 12:20
  • Depends on what you want to achieve Commented Dec 27, 2018 at 12:20

1 Answer 1

1

You can destructure array elements like

let [first, second, ...rest] = str.split(',');

Basically it works by index, the first variable being arr[0], second being arr1 and so on. ...rest will hold the remaining items in the array which aren't destrucutred

Check the MDN documentation for Array Destructuring

Sign up to request clarification or add additional context in comments.

1 Comment

You should avoid answering questions that have duplicates that answer the questions in detail (Based on your profile, I see you're doing this frequently). You should at least take the time to select and link the duplicates. If the questions are answered again and again, there will be thousands of short and badly answered questions and the well answered questions will be lost.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.