简体   繁体   中英

javascript - How to merge each element in array with other elements in different array?

Lets say that we have 2 arrays we want to return one array that contains each array1[element] + ( rest of elements in array 2 ) and so on.

let array1 = ["a","b"];
let array2 = ["e","f"];

let array3 = mergeArrays(array1,array2);// ["ae","af","be","bf"]

// I tried something like this

let output = [];
let x = 0;
for (let i = 0;i< variants.length;i++){
   for (let j = 0;j < variants[i].length;j++){
       output[x] = variants[i][x] + variants[j][x];
       x++;
   }
}

With two maps and flattening:

 let array1 = ["a","b"]; let array2 = ["e","f"]; let array3 = array1.map(a => array2.map(b => a + b)).flat(); console.log(array3); 

You can simply use nested for ( ...of ) loops to generate the Cartesian product of two arrays:

 let array1 = ["a", "b"]; let array2 = ["e", "f"]; function mergeArrays(arr1, arr2) { let res = []; for (i of arr1) { for (j of arr2) { res.push(i + j); } } return res; } let array3 = mergeArrays(array1, array2); console.log(array3); 

Even shorter than mbojko's answer :

 let array1 = ["a","b"]; let array2 = ["e","f"]; let array3 = array1.flatMap(a => array2.map(b => a + b)); console.log(array3); 

This uses the Array.prototype.flatMap() method.


In fact, you can extend this to support any number of arrays:

 function cartesian (reducerFn) { return function zip (array, ...arrays) { if (arrays.length === 0) return array; const values = zip(...arrays); return array.flatMap(a => values.map(b => reducerFn(a, b))); }; } const mergeArrays = cartesian((a, b) => a + b); let array1 = ["a","b"]; let array2 = ["c","d"]; let array3 = ["e","f"]; let array4 = mergeArrays(array1, array2, array3); console.log(array4); 

Using ES6:

 const array1 = ["a","b"]; const array2 = ["e","f"]; const result = array1.reduce((acc, curr) => { const product = array2.map(el => curr + el); acc.push(...product) return acc; }, []); console.log(result); 

Loop through first array with Array.prototype.reduce and foreach item get the product with second array, push to accumulator and repeat for each element in first array to get the result.

To make concatenation more predictable (in case of input other than string) I'd use ` ${curr}${el} ` instead of curr + el . It's up to your needs though!

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