Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

191
Vistas
Generating all combinations of elements in a single array (for cominations of N elements)

I'm trying to build/find a function, which will give me all combinations for N number of elements.

The solution below gives me an answer for pairs (i.e. 2 elements).

I'd like to parameterize it, so that I can define the number of combined elements (e.g. 3 elements => ['one', 'two', 'three'], ['one', 'two', 'four'], ... , 4 elements, and so on.

(Bonus internet points if you can tell me the name what I'm looking for (cartesian-product?)!)

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 Respuestas
Responde la pregunta

0

I think this is your solution.

/** 
 * 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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda