Skip to content
Advertisement

JavaScript: Split array into individual variables

Considering this data structure:

var vehicles = [
  [ "2011","Honda","Accord" ],
  [ "2010","Honda","Accord" ],
  .....
];

Looping through each vehicles item, is there a way to reassign the array elements to individual variables all in one shot, something like:

for (i = 0; i < vehicles.length; i++) {
  var(year,make,model) = vehicles[i]; // doesn't work
  .....
}

… I’m trying to get away from doing:

for (i = 0; i < vehicles.length; i++) {
  var year = vehicles[i][0];
  var make = vehicles[i][1];
  var model = vehicles[i][2];
  .....
}

Just curious since this type of thing is available in other programming languages. Thanks!

Advertisement

Answer

Now it is possible using ES6’s Array Destructuring.

As from Docs:

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Consider the following example:

let [a, b, c] = [10, 20, 30];

console.log(a);  // output => 10
console.log(b);  // output => 20
console.log(c);  // output => 30

As with your data, .forEach() method can also be used for iterating over array elements along with Array Destructuring:

let vehicles = [
  [ "2011","Honda","Accord" ],
  [ "2010","Honda","Accord" ]
];

vehicles.forEach(([year, make, model], index) => {
  // ... your code here ...
  console.log(`${year}, ${make}, ${model}, ${index}`);
});

References:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement