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)
}
diegoaguilar
  • 8,179
  • 14
  • 80
  • 129
  • This operation is called ["zip"](http://stackoverflow.com/questions/1115563/what-is-zip-functional-programming) and can be found in such libraries as underscorejs. ES6/Harmony will additionally have [generator support](http://domenic.me/2013/09/06/es6-iterators-generators-and-iterables/). – user2864740 Feb 12 '14 at 05:57

2 Answers2

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.

frosty
  • 21,036
  • 7
  • 52
  • 74
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.

adeneo
  • 312,895
  • 29
  • 395
  • 388