3

I have two arrays currently

array1 = [5, 10, 20]
array2 = [10, 20, 30]

Either array3 or something like this:

array4 = [{"a":5, "b":10}, {"a":10, "b":20}, {"a":20, "b":30}]

I know this is probably an easy question but I'm not even sure what array3 would be called so its kind of hard to google this.

Cristiano
  • 2,559
  • 6
  • 22
  • 34

3 Answers3

8

Very simple, first we create a result array, then we iterate through the first array and add elements to it. Here is a working fiddle.

Note, in your code you have notation like {5,10} which is illegal in JavaScript, I assumed you mean an array.

var result = [];
for(var i=0;i<array1.length;i++){
   result.push([array1[i],array2[i]]);
}

Update after edit , it seems like you want objects, try

var result = [];
for(var i=0;i<array1.length;i++){
   result.push({a:array1[i],b:array2[i]});//add object literal
}

If you'd like, you can also use map and write the same code functionally. Here is a fiddle of that sort of implementation

Benjamin Gruenbaum
  • 246,787
  • 79
  • 474
  • 476
2

This is called zip...

function zip() {
    var args = [].slice.call(arguments);
    var shortest = args.length==0 ? [] : args.reduce(function(a,b){
        return a.length<b.length ? a : b
    });

    return shortest.map(function(_,i){
        return args.map(function(array){return array[i]})
    });
}

Check Underscore a fantastic js library with many of these utility functions...

Teja Kantamneni
  • 16,851
  • 10
  • 54
  • 84
  • Note, this will fail on many browsers since it relies on methods such as `reduce` and `map` which need to be shimmed first. – Benjamin Gruenbaum Mar 21 '13 at 19:52
  • @thg435 Yes, I mean IE8, IE7 and IE6 which are sadly still widely used (IE6 is still over 20% of chine :( ) . I think the answer is ok, however anyone using this code should be aware of the need to shim map and reduce if you intend to support some browsers. – Benjamin Gruenbaum Mar 21 '13 at 20:27
2

You can do this easily with ES6 new feature

 var  array1 = [5, 10, 20];
   var   array2 = [10, 20, 30];
  var combineArray = [...array1 , ...array2];
       //output should be like this of combine array : [5, 10 ,20 ,10 ,20 ,30]

if you want to extra item inside two array then you can do this using below way :

 var combineArray = [...array1 ,333, ...array2];
           //output should be like this of combine array : [5, 10 ,20 ,333 ,10 ,20 ,30] 
Hoque MD Zahidul
  • 5,772
  • 2
  • 26
  • 34