3

I have two arrays of arrays where the first contains the location name and the second contains the location latitude and longitude values. Each item in each array corresponds to it's counterpart in the other and both arrays have the same number of items like so:

var arr1 = [['Location #1'],['Location #2']];
var arr2 = [['36.1978319','-83.02365759999999'],['38.679842','-121.7457402']];

What I need is a combined array of the two sets of items, but not concatenated like so:

var arr3 = [['Location #1','36.1978319','-83.02365759999999'],
           ['Location #2','38.679842','-121.7457402']];

The only way I can think of doing this would be with like a combined for loop, but I can't get the syntax correct and not sure this is even possible... something like this:

for ((var a = 0; a < arr1.length; a++) && (var b = 0; b < arr2.length; b++)) {
    arr3.push(arr1[a] + ',' + arr2[b]);
}

Is there a way to solve this problem with pure javascript?

cweiske
  • 30,033
  • 14
  • 133
  • 194
Lars
  • 347
  • 4
  • 11
  • Run the loop for Arr1.length ,as the final arr3 length will be same as arr1 and join each element of arr1 and arr2, that will get you the expected result – Naga Sai A Jun 23 '16 at 15:46
  • Is there any particular reason why you want this all in an indexed array? You might consider storing the locations as regular objects {} with keys/values for the locations and coordinates. It would be much more semantically meaningful. – skyline3000 Jun 23 '16 at 15:47
  • @skyline3000 - I don't have any control over how the geocoded location items are being returned or else I would have absolutely used objects. You are correct, that would be the way to go. – Lars Jun 23 '16 at 16:05

3 Answers3

7

I suggest Array.map for its shortness:

var arr1 = [['Location #1'], ['Location #2']];
var arr2 = [['36.1978319', '-83.02365759999999'], ['38.679842', '-121.7457402']];

var combined = arr1.map((element, i) => element.concat(arr2[i]));

console.log(combined);

For a more generic solution (combining an arbitrary number of arrays), refer to Javascript equivalent of Python's zip function

Community
  • 1
  • 1
le_m
  • 19,302
  • 9
  • 64
  • 74
  • @le_m This worked beautifully! Kudos... and thank you for this perfect minimal solution – Lars Jun 23 '16 at 16:00
3

If the two arrays really are equal in length, and correspond in index. This is all you need:

for (var a = 0; a < arr1.length; a++) {
    arr3.push(arr1[a] + ',' + arr2[a]);
}
Blunderfest
  • 1,854
  • 1
  • 28
  • 46
1

You are trying to combine 2 contors inside a for loop :).

You want to do this:

 var resultArray = new Array();
 for (var i = 0; i < arr1.length; i++) {
     resultArray.push([arr1[i], arr2[i][0], arr2[i][1]]);
 }
zozo
  • 8,230
  • 19
  • 79
  • 134