0

I tried to generate and array of arrays, beign the inner array elements the tuples from two other arrays.

Like:

xArray = [x1,x2,x3,x4...xn]
yArray = [y1,y2,y3,y4...yn]

And I need to get a generated array of the from:

points = [[x1,y1],[x2,y2],[x3,y3]...[xn,yn]]

I'm a bit aware of python expressions where you can generate an array assigning the values as an expression. But how could I do this in JavaScript?

Of course I had to go for a cycle:

for (var i = 0;i<xs.length;i++) {

    var pt=[]
    pt.push(xs[i])
    pt.push(ys[i])
    pts.push(pt)
}
1
  • This operation is called "zip" and can be found in such libraries as underscorejs. ES6/Harmony will additionally have generator support. Commented Feb 12, 2014 at 5:57

2 Answers 2

1
var points = [], i = 0;
for(i = 0; i < xArray.length; i++){
    points.push([xArray[i], yArray[i]]);
}
//points is loaded with your data format. 

If you were using lodash, you could use the following

var points = _.zip(xArray, yArray);

I recommend lodash, especially if you are going to continue to do a significant data manipulation.

Sign up to request clarification or add additional context in comments.

Comments

1

You'd have to map the arrays into another array. Something like this

var points = xArray.map(function(itm, i) {
    return [itm, yArray[i]]; // assuming they have the same length
});

FIDDLE

This uses Array.map, there's a polyfill on MDN if older browsers is an issue.

1 Comment

Thanks, aren't functional like statements allowed in JavaScript?

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.