A continuación se muestra la función de combinación ampliamente conocida.
function getCombination(arr,selectNumber){ const result = []; if(selectNumber == 1) { return arr.map(el => [el]) }; arr.forEach((fixed, index, array)=>{ const rest = array.slice(index+1); const combinations = getCombination(rest, selectNumber - 1); const attached = combinations.map((el => [fixed,...el])); result.push(...attached); }); return result; };Rastreé el código y encontré algunos cálculos inútiles cuando (index == array.length-1) en forEach segmento. así que agregué "if ()" en eso. ¿siempre devuelve resultados correctos?
function getCombination(arr,selectNumber){ const result = []; if(selectNumber == 1) { return arr.map(el => [el]) }; arr.forEach((fixed, index, array)=>{ if(index == array.length-1) return; /* I added this line */ const rest = array.slice(index+1); const combinations = getCombination(rest, selectNumber - 1); const attached = combinations.map((el => [fixed,...el])); result.push(...attached); }); return result; };