从2个现有阵列创建自定义阵列

时间:2018-02-08 11:19:41

标签: javascript

我有2个像这样的数组,

array_1 = [1,2,3]
array_2 = [a,b] 

我想在kurasulst中获得6个数组,如下面的结果。

[1,a]
[1,b]
[2,a]
[2,b]
[3,a]
[3,b]

我试过但没有成功。

var rowCount = array_1.length + array_2.length; 
console.info("rowCount",rowCount);
var array_1Repeat = rowCount/(array_1.length);
var array_2Repeat = rowCount/(array_2.length);
console.info("array_1Repeat",array_1Repeat);
console.info("array_2Repeat",array_2Repeat);

var kurasulst =[];
for(var i=0; i<rowCount.length; i++){
    console.info("array_1[i]",array_1[i]);
    var kurasu = {array_1:array_1[i],array_2:array_2[i] };

kurasulst.push(kurasu);
}

请帮助我。

4 个答案:

答案 0 :(得分:3)

您可以使用reducemap

var output = array_1.reduce( ( a, c ) => a.concat( array_2.map( s => [c,s] ) ),  []);

<强>演示

var array_1 = [1,2,3];
var array_2 = ["a","b"];
var output = array_1.reduce( (a, c) =>  a.concat(array_2.map( s => [c,s] )),  []);
console.log( output );

答案 1 :(得分:2)

试试这个:

var kurasulst = [];
for (var i = 0; i < array_1.length; i++) {
    for (var j = 0; j < array_2.length; j++) {
        kurasulst.push([array_1[i], array_2[j]]);
    }
}
console.log(kurasulst);

答案 2 :(得分:1)

您可以执行以下操作:

var array_1 = [1,2,3];
var array_2 = ['a','b']; 

var res = [];
array_1.forEach(function(item){
  res2 = array_2.forEach(function(data){
    var temp = [];
    temp.push(item);
    temp.push(data);
    res.push(temp);
  });
});

console.log(res);

答案 3 :(得分:1)

您可以使用其他方法,使用任意数组的数组(种类),例如

var items = [[1, 2, 3], ['a', 'b']],
    result = items.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

有两个以上

var items = [[1, 2, 3], ['a', 'b'], ['alpha', 'gamma', 'delta']],
    result = items.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));

console.log(result.map(a => a.join()));
.as-console-wrapper { max-height: 100% !important; top: 0; }