Reputation: 357
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?
Upvotes: 3
Views: 150
Reputation: 20228
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
Upvotes: 7
Reputation: 8582
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]]);
}
Upvotes: 1
Reputation: 1854
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]);
}
Upvotes: 3