11/13/2017 - 1:56 PM

ES6 - Destructuring Array's

A feature I tend to forget about in es6 is the possibility to destructure arrays as well. Instead of curly brackets you use with an object, you use square brackets and as arrays do not have keys, array destructuring is based on the position of the values in the element.These are a couple of array destructuring examples from

const details = ['Arden', 123, ''];
// get a bunch of values out of the details array and name them as variable
const [name, id, website] = details;
console.log(name, id, website);

const data = 'Basketball,Sports,90210,23,super,man,cool';
// We use data.split(',') which takes in the data string and returns it as an
// array which we immediately destructure with es6 array destructuring. 

// When we have values that we do not call while destructuring, nothing will
// happen with them.
const [itemName, category, sku, inventory] = data.split(',');

const team = ['Cap', 'Hulk', 'Black Widow', 'Iron Man', 'Thor'];
// Here we destructure the first and second values from the team array and return 
// them in variables called `captain` and `assistant`. We use the `rest` operator (`...`) to
// spread out the remaining values in an array called `players`
const [captain, assistant, ...players] = team;