Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

197
Views
Generación de todas las combinaciones de elementos en una sola matriz (para combinaciones de N elementos)

Estoy tratando de construir/encontrar una función, que me dará todas las combinaciones para N número de elementos.

La siguiente solución me da una respuesta para pares (es decir, 2 elementos).

Me gustaría parametrizarlo, para poder definir el número de elementos combinados (por ejemplo, 3 elementos => ['one', 'two', 'three'], ['one', 'two', 'four'], ... , 4 elementos, etc.

(¡Puntos extra de Internet si puedes decirme el nombre de lo que estoy buscando (¿producto cartesiano?)!)

 var array = ['one', 'two', 'three', 'four', 'five'] // get pairs var result = array => array.flatMap((v, i) => array.slice(i+1).map( w => [v, w] )); console.log(result(array)) // output: // [ // ["one", "two"], // ["one", "three"], // ["one", "four"], // ["one", "five"], // ["two", "three"], // ["two", "four"], // ["two", "five"], // ["three", "four"], // ["three", "five"], // ["four", "five"] // ]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Creo que esta es tu solución.

 /** * Usage Example: * * console.log(combination(['A', 'B', 'C', 'D'], 2, true)); // [[ 'A','A' ], [ 'A', 'B' ]...] (16 items) * console.log(combination(['A', 'B', 'C', 'D'])); // [['A', 'A', 'A', 'B' ],.....,['A'],] (340 items) * console.log(comination(4, 2)); // all posible values [[ 0 ], [ 1 ], [ 2 ], [ 3 ], [ 0, 0 ], [ 0, 1 ], [ 0, 2 ]...] (20 items) */ function combination(item, n) { const filter = typeof n !=='undefined'; n = n ? n : item.length; const result = []; const isArray = item.constructor.name === 'Array'; const pow = (x, n, m = []) => { if (n > 0) { for (var i = 0; i < 4; i++) { const value = pow(x, n - 1, [...m, isArray ? item[i] : i]); result.push(value); } } return m; } pow(isArray ? item.length : item, n); return filter ? result.filter(item => item.length == n) : result; } console.log("#####first sample: ", combination(['A', 'B', 'C', 'D'], 2)); // with filter console.log("#####second sample: ", combination(['A', 'B', 'C', 'D'])); // without filter console.log("#####third sample: ", combination(4, 2)); // just number
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!