简体   繁体   中英

Combine two arrays into one array javascript

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.

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

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...

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] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM