Reputation: 1159
I have two separate arrays which looks something like this
var x = ['one', 'two', 'three'];
var y = ['1', '2', '3'];
I am doing this to combine them
var newArray = [];
for (var i = 0; i < x.length && i < y.length; i++) {
newArray[i] = [x[i], y[i]];
}
desired output
newArray = [
['one', '1'],
['two', '2'],
['three', '3']
]
This is my fiddle: http://jsfiddle.net/sghoush1/EjRPS/4/
Upvotes: 2
Views: 774
Reputation: 339786
On ES5 you can use Array.prototype.map
to simplify your loop:
var newArray = x.map(function(n, i) {
return [n, y[i]];
});
See the above link for a shim for older browsers.
If you have Underscore.js, you can use:
var newArray = _.zip(x, y);
Upvotes: 3