简体   繁体   English

将两个数组合并为一个数组javascript

[英]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: 无论是array3还是类似的东西:

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. 我知道这可能是一个简单的问题,但我甚至不确定会调用哪个array3所以很难谷歌这个。

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. 请注意,在您的代码中,您有{5,10}这样的符号,这在JavaScript中是非法的,我假设您的意思是数组。

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. 如果您愿意,还可以使用map并在功能上编写相同的代码。 Here is a fiddle of that sort of implementation 这是这种实现的小提琴

This is called zip ... 这叫做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... 使用许多这些实用程序功能检查Underscore是一个很棒的js库...

You can do this easily with ES6 new feature 您可以使用ES6新功能轻松完成此操作

 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] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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