-2

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]]
Stephen Docy
  • 4,738
  • 7
  • 18
  • 31
Patrick Sampaio
  • 390
  • 2
  • 13
  • Possible duplicate of [How to concatenate properties from multiple JavaScript objects](http://stackoverflow.com/questions/2454295/how-to-concatenate-properties-from-multiple-javascript-objects) – farhan May 18 '17 at 18:30
  • Before asking any question do read https://stackoverflow.com/help/how-to-ask – farhan May 18 '17 at 18:31
  • Have you at least tried? You need a simple `for` loop. – nonzaprej May 18 '17 at 18:32

3 Answers3

0

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));
JellyKid
  • 302
  • 1
  • 6
0

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);
}
Woodrow
  • 2,740
  • 1
  • 14
  • 18
0

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392