在JavaScript中以所有可能的方式将2个数组合并为1

时间:2017-07-04 18:11:17

标签: javascript

我的目标是以所有可能的方式合并2个数组,第一个数组将始终是单元格的第一部分,第二个数组将始终位于单元格的第二部分。 /> 我的最后一次尝试,最接近但不完全是我需要的:

function combineArrays(array1, array2) {
    let arr = [];
    for (let i = 0; i < array1.length; i++) {
        arr[i] = array1[i];
    }
    for (let i = 0, j = 0; i < array1.length; i++) {
        arr[i] += array2[j];
        if (array2[j + 1]) {
            j++;
        }
        else {
            j = 0;
        }
    }
    return arr;
}

编辑:
例如,数组A和数组B:
答:[&#34;我&#34;,&#34;你&#34;,&#34;他&#34;,&#34;她&#34; ]
B:[&#34; am&#34;,&#34;是&#34;,&#34;&#34;&#34; ]

预期结果:
[
&#34;我是&#34;,&#34;你是&#34;,&#34;他是&#34;,&#34;她是&#34;,
&#34;我是&#34;,&#34;你是&#39;,&#34;他是&#34;,&#34;她是&#34;,
&#34;我是&#34;,&#34;你是&#34;,&#34;他是&#34;,&#34;她是&#34;
]

3 个答案:

答案 0 :(得分:1)

let a = ["I", "You", "He", "She"];
let b = ["am", "is", "are"];
let result = b.map(b => a.map(a => a + ' ' + b));

console.log(result);

如果您不想要嵌套数组:

let a = ["I", "You", "He", "She"];
let b = ["am", "is", "are"];
let result = b.reduce((arr, b) => arr.concat(a.map(a => a + ' ' + b)), []);

console.log(result);

对于n数量的数组:

    let a = ["I", "You", "He", "She"];
    let b = ["am", "is", "are"];
    let c = ["good", "bad", "happy"];
    let crossProduct = (a, b) => b.reduce((arr, b) => arr.concat(a.map(a => a + ' ' + b)), []);
    
    let result = [a, b, c].reduce(crossProduct);

    console.log(result);

答案 1 :(得分:0)

var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];

var arr3 = arr1.concat(arr2);

// arr3 is a new array [ "a", "b", "c", "d", "e", "f" ]

但是你似乎想要对你实现的数组求和:

var array1 = [1,2,3,4];
var array2 = [5,6,7,8];

var sum = array1.map(function (num, idx) {
  return num + array2[idx];
}); 
// [6,8,10,12]

答案 2 :(得分:0)

如果您的目标是合并两个数组,那么这是ES6方式:

const arr1 = ['a', 'b', 'c'];
const arr2 = ['d', 'e', 'f'];

const arr3 = [...arr1, ...arr2]; // Output: [ "a", "b", "c", "d", "e", "f" ]

但是,在你的情况下(编辑之后),你想要做更多的事情!

const arr1 = [ "I", "You", "He", "She" ];
const arr2 = [ "am", "is", "are" ];

arr2.map(eltB => arr1.map(eltA => `${eltA} ${eltB}`))
    .reduce((newArray, arr) => newArray.concat(arr), []);