Given the following arrays:
var arr1 = ['A','B','C'];
var arr2 = [['D','E','F']['G','H','I']]
The output should be:
['ADG','ADH','ADI','AEG','AEH','AEI','AFG','AFH','AFI','BDG','BDH','BDI'.....]
But it should also be dynamic so that if another array is added to arr2 it should pick that as well.
This is what I currently have:
const arrays = (arr1 = [], arr2 = [],arr3 = []) => {
// var arr3 = arr2.slice(3);
const res = [];
for(let i = 0; i < arr1.length; i ){
for(let j = 0; j < arr2.length; j ){
for(let s=0;s<arr3.length;s ){
res.push(arr1[i] arr2[j] arr3[s] );
}
}
}
return res;
};
CodePudding user response:
The fact that you have those two different array variables is immaterial. Could just throw everything together1 and use reduceRight()
:
const arrays = [['A','B','C'], ['D','E','F'], ['G','H','I']];
const combine = (arrays) =>
arrays.reduceRight((a, v) => v.flatMap(c => a.map(r => c r)));
console.log(combine(arrays));
1 For your case that would be as simple as const arrays = [arr1, ...arr2];
CodePudding user response:
var arr1 = ['A','B','C'];
var arr2 = [['D','E','F'],['G','H','I'],['J','K','L'],['M','N','O']];
const arr3 = [];
arr1.forEach((item,index)=>{
if(arr2.length >= index)
{
arr2.forEach((el,i)=>{
el.forEach((char,charIndex)=>{
let combination = item
combination = char
for(let j=1;j<arr2.length;j ){
if(arr2[j]){
combination = arr2[j][charIndex]
}
}
arr3.push(combination)
})
})
}
})
console.log(arr3)
here is what I did