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 c
Solution 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);
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"];
letcrossProduct = (a, b) => b.reduce((arr, b) => arr.concat(a.map(a => a + ' ' + b)), []);
let result = [a, b, c].reduce(crossProduct);
console.log(result);
Solution 2:
var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];
var arr3 = arr1.concat(arr2);
// arr3 is a newarray [ "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]
Solution 3:
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), []);
Post a Comment for "Combine 2 Arrays Into 1 In All Possible Ways In Javascript"