Dadas las siguientes matrices:
var arr1 = ['A','B','C']; var arr2 = [['D','E','F']['G','H','I']]
La salida debe ser:
['ADG','ADH','ADI','AEG','AEH','AEI','AFG','AFH','AFI','BDG','BDH','BDI'.....]
Pero también debe ser dinámico, de modo que si se agrega otra matriz a arr2, también debería seleccionarla.
Esto es lo que tengo actualmente:
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; };
El hecho de que tenga esas dos variables de matriz diferentes es irrelevante. Podría juntar todo 1 y usar 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 Para su caso, eso sería tan simple como const arrays = [arr1, ...arr2];
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)
Aquí esta lo que hice