2

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/

8
  • @thanks david..I think you caught it before I did. Thanks for the correction Commented Aug 25, 2013 at 20:18
  • 1
    Looking at the console, your desired output seems to be what you get. And, for the edit, you're quite welcome. =) Commented Aug 25, 2013 at 20:18
  • i think your code is working Commented Aug 25, 2013 at 20:19
  • Your fiddle is working perfectly fine. What's the problem, how do you think the output differs? Commented Aug 25, 2013 at 20:19
  • 1
    @ScottSauyet because that's the name this function had in traditional functional programming languages, e.g. LISP. Commented Aug 25, 2013 at 20:31

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.