简体   繁体   中英

Combine 2 arrays into 1 in all possible ways in JavaScript

My goal is to merge 2 arrays in all possible ways, in a way that, the 1st array will always be the first part of the cell, and the 2nd array will always be in the 2nd part of the cell.
My last attempt, which is the closest but not exactly what I need:

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;
}

Edit:
For example, array A and array B:
A: [ "I", "You", "He", "She" ]
B: [ "am", "is", "are" ]

Expected result:
[
"I am", "You am", "He am", "She am",
"I is", "You is', "He is", "She is",
"I are", "You are", "He are", "She are"
]

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

If you don't want the nested arrays:

 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); 

For n amount of arrays:

  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); 

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" ]

but you seem you want to sum array that you achieve like this:

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]

If your goal is to merge two arrays, here is the ES6 way:

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

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

But, in your case (after your edit), you want to do more!

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), []);

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