I have those arrays
var array = ["name1", "name2"];
var array2 = [4,5];
And i need to merge them like this
var result = [[name1, 4], [name2, 5]]
I have those arrays
var array = ["name1", "name2"];
var array2 = [4,5];
And i need to merge them like this
var result = [[name1, 4], [name2, 5]]
function weave(a,b) {
if(a.length != b.length){
return -1;
}
let res = [];
for (var i = 0; i < a.length; i++) {
res.push([a[i],b[i]]);
}
return res;
}
var array = ["name1", "name2"];
var array2 = [4,5];
console.log(weave(array, array2));
Your question isn't formatted properly. If you're looking to concatenate the two arrays, you would do:
var result = array.concat(array2);
However, if you're trying to match the indexes of the 2 arrays to make result like your example, (and assuming the arrays are the same length) you can do:
var array = ["name1", "name2"];
var array2 = [4, 5];
if (array.length === array2.length) {
var result = [];
for (i = 0; i < array.length; i++) {
var subArray = []
subArray.push(array[i]);
subArray.push(array2[i]);
result.push(subArray);
}
console.log(result);
}
You could use an array of the given data and iterate. Then take the index of the inner array for the outer result array and push the value to the index.
var array1 = ["name1", "name2"],
array2 = [4, 5],
result = [array1, array2].reduce(function (r, a) {
a.forEach(function (b, i) {
r[i] = r[i] || [];
r[i].push(b);
});
return r;
}, []);
console.log(result);