Unpacking array into separate variables in JavaScript

JavascriptArrays

Javascript Problem Overview


This is a simple problem, and I've done it before. I just can't remember how, or what exactly it was called.

In python I can do this:

arr = ['one', 'two']
one, two = arr

how do I do that in JavaScript?

Javascript Solutions


Solution 1 - Javascript

This is currently the only cross-browser-compatible solution AFAIK:

var one = arr[0],
    two = arr[1];

ES6 will allow destructuring assignment:

let [x, y] = ['foo', 'bar'];
console.log(x); // 'foo'
console.log(y); // 'bar'

Or, to stick to your initial example:

var arr = ['one', 'two'];
var [one, two] = arr;

You could also create a default value:

const [one = 'one', two = 'two', three = 'three'] = [1, 2];
console.log(one); // 1
console.log(two); // 2
console.log(three); // 'three'

Solution 2 - Javascript

The question is rather old but I like to post this alternative (2016) solution: One can also use the spread operator "...".

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

let xAndY = [42, 1337];
let f = function(x, y) { return x + y; };
f(...xAndY);

Solution 3 - Javascript

That's destructuring assignment. You can do it in some browsers with the following syntax:

[one, two] = arr;

It's supported in some of the latest browsers and transpilers like Babel and Traceur. This was a feature introduced with ECMAScript 4 which later became ECMAScript Harmony, which eventually became ES 2015.

Solution 4 - Javascript

You can use array's apply function if you want an array items to be passed as a function arguments.

Solution 5 - Javascript

Implementation of serious's idea.

http://jsfiddle.net/RichAyotte/6D2wP/

(function(a, b, c, d) {
	console.log(a, b, c, d);   
}.apply(this, ['a', 'b', 'c', 'd']));

Solution 6 - Javascript

var one = arr[0];
var two = arr[1];

Solution 7 - Javascript

CoffeeScript has it: http://jashkenas.github.com/coffee-script/#pattern_matching

And, quoted from the top of the page:

"CoffeeScript is a little language that compiles into JavaScript. Think of it as JavaScript's less ostentatious kid brother — the same genes, roughly the same height, but a different sense of style. Apart from a handful of bonus goodies, statements in CoffeeScript correspond one-to-one with their equivalent in JavaScript, it's just another way of saying it."

Solution 8 - Javascript

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

Here is an example. You can try like this.

 let a, b, rest;
[a, b] = [10, 20];

console.log(a);
// expected output: 10

console.log(b);
// expected output: 20

[a, b, ...rest] = [10, 20, 30, 40, 50];

console.log(rest);
// expected output: Array [30,40,50]

Solution 9 - Javascript

My example works for your example but also if you dont know the array or the array length.

arr = ['one', 'two'];
var length = arr.length;
for (var i = 0; i < length; i++)
{
   var val = arr[i];
   eval('var '+arr[i]+'= arr[i];');
}

Know you have 2 variables. The first is 'one' who is "one"and the second is 'two' who is "two". Your problem is solved! But for the code snippet, i created extra elements to display the var's and i logged it.

arr = ['one', 'two'];
var length = arr.length;
for (var i = 0; i < length; i++)
{
   var val = arr[i];
   eval('var '+arr[i]+'= arr[i];');
}
var p = document.createElement("p");
p.innerHTML = one + " " + two;
document.body.appendChild(p);
console.log(one, two);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCarson MyersView Question on Stackoverflow
Solution 1 - JavascriptMathias BynensView Answer on Stackoverflow
Solution 2 - JavascriptChris KView Answer on Stackoverflow
Solution 3 - JavascriptAndy EView Answer on Stackoverflow
Solution 4 - JavascriptseriousView Answer on Stackoverflow
Solution 5 - JavascriptRichard AyotteView Answer on Stackoverflow
Solution 6 - Javascriptrob waminalView Answer on Stackoverflow
Solution 7 - JavascriptJakobView Answer on Stackoverflow
Solution 8 - JavascriptAbdus Salam AzadView Answer on Stackoverflow
Solution 9 - JavascriptRobbe CleversView Answer on Stackoverflow