Unpacking array into separate variables in JavaScript
Asked Answered
A

10

184

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?

Afghani answered 6/8, 2010 at 9:20 Comment(0)
S
241

ES6 allows for 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'
Stripy answered 6/8, 2010 at 9:24 Comment(2)
destructuring assignment has full support as of today kangax.github.io/compat-table/es6/#test-destructuringMisspend
not true, now can be done with the spread syntax: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Teador
A
33

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);
Achates answered 21/9, 2016 at 7:51 Comment(0)
M
30

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.

Mandler answered 6/8, 2010 at 9:23 Comment(2)
Looks like it's part of ES6 (2015), not ES4? ecma-international.org/ecma-262/6.0/…Machicolation
@jab: thanks! sometimes these old answers get forgotten about and become outdated, though it looks like Mathias already added that info to his answer :)Mandler
L
7

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

Lolita answered 18/8, 2010 at 9:55 Comment(1)
I'm not sure a JavaScript Array has an .apply() function. I think you meant some_function.apply(this, my_array). See this answerPyroxene
B
6

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']));
Bisson answered 6/1, 2014 at 16:28 Comment(1)
This one made my day. Unpacking lists via apply, well done sir!Coltson
K
3
var one = arr[0];
var two = arr[1];
Keratosis answered 6/8, 2010 at 9:23 Comment(3)
You should really use var to prevent the variables from polluting the global scope.Stripy
I'm just assuming its all declared variables :)Keratosis
It’s probably a better idea to declare all var s for each scope in one go rather than having two separate var declarations.Stripy
M
3

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]
Magdalen answered 25/10, 2021 at 6:22 Comment(0)
F
2

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."

Forbear answered 6/8, 2010 at 9:35 Comment(2)
This doesn't answer the question. I appreciate that CoffeeScript has some neat things, but the question is about Javascript.Lira
Dead link :((((Subminiaturize
K
0

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);
Koenig answered 30/7, 2021 at 17:15 Comment(0)
C
0
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);
Cinchonize answered 7/6, 2022 at 12:33 Comment(1)
Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you’ve made.Burger

© 2022 - 2024 — McMap. All rights reserved.