0

I have two one dimensionaly arrays - each of the same length; temperature and seconds. To create a scatter graph, I need it in the form;

var data = [
            [temperature[100],seconds[100]],
            [temperature[99],seconds[99]],
            [temperature[98],seconds[98]],
             ...
           ];

I can't seem to work out how to do it, and I seem to be asking the wrong questions in Google.

1
  • search for 'zip javascript arrays' next time Commented Nov 5, 2011 at 10:22

2 Answers 2

2

Loop backwards through the arrays and create new arrays from each pair of items:

var data = [];
for (var i = temperature.length - 1; i >= 0 ; i--) {
  data.push([ temperature[i], seconds[i] ]);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Why loop backwards here? Aren't you resizing the array each time anyway by using push?
@Triptych: Because the last elements of the temperature and seconds array should come first.
@Triptych: I chose to loop backwards because the result has the data backwards. Using push is somewhat slower, but it makes for simpler code here. You can make it faster by creating the array with the final size, and by setting the items using the index instead of using push, but there is no dramatic difference. Arrays work a little different in various browsers, in Firefox for example it doesn't make any difference at all if you create the array with the final size or create an empty array and let it grow.
@Guffa - I missed the obvious reason - that it was reversed in the OP's output. Good info about push behavior tho - thanks =). And I should have said "-potentially- resizing the array"
@Triptych Thanks for that :) The array was used in a scatter plot, so the ordering ending up being unimportant (whereas when I was trending just a line, it was). Worked great nonetheless!
0

I think this the solution to your problem, though not tested.

data = [];
for(var i = 0, len = temperature.lengh - 1;i < len; i++){
  data[i] = [temperature[len  - i] , seconds[len - i]];
}

1 Comment

I think on the line inside the loop the [len - i] indexes should be [len - i - 1], because the last item in the array is at an index equal to the length minus 1. Either that or change the loop initialisation and condition: for(var i=0; len=temperature.length-1; i<=len; i++).

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.