Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpacking array into separate variables in JavaScript

People also ask

How do you split an array in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do you separate an array of arrays?

Splitting the Array Into Even Chunks Using slice() Method The easiest way to extract a chunk of an array, or rather, to slice it up, is the slice() method: slice(start, end) - Returns a part of the invoked array, between the start and end indices.

How do you Destructure an array of objects?

To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element.

How do you split an array of numbers?

To split a number into an array:Call the split() method on the string to get an array of strings. Call the map() method on the array to convert each string to a number.


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'

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);

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.


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