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

194
Vistas
How do array permutation splitting by (n)

So I have array

const arr = [ 1, 4, 5, 8]

I want to get all possible combinations of this array splitted by (n) number for example

function getNPermutate(arr, n) {
 
}

getNPermutate(arr, 3) // [[1, 4, 5], [1, 4, 8], [4, 5, 8],[1, 5 ,8] ]

!array can be any length

I found the solution with simple permutation, but dont understand how do splitted permutation

 function permute(nums) {
  let result = [];
  if (nums.length === 0) return [];
  if (nums.length === 1) return [nums];
  for (let i = 0; i < nums.length; i++) {
    const currentNum = nums[i];
    const remainingNums = nums.slice(0, i).concat(nums.slice(i + 1));
    const remainingNumsPermuted = permute(remainingNums);
   for (let j = 0; j < remainingNumsPermuted.length; j++) {
      const permutedArray =  [currentNum].concat(remainingNumsPermuted[j]);
      result.push(permutedArray);
    }
  }
  return result;
}

console.log(permute([1,2,3,4]))
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can try this one:

Script:

function test() {
  var array = [1, 4, 5, 8];

  console.log(getCombinations(array, 3)) 
}

function getCombinations(chars, len) {
  var result = [];
  var f = function(prefix, chars) {
    for (var i = 0; i < chars.length; i++) {
      var elem = [...prefix, chars[i]];
      if(elem.length == len)
        result.push(elem);
      f(elem, chars.slice(i + 1));
    }
  }
  f([], chars);
  return result;
}

Output:

output

about 4 years ago · Juan Pablo Isaza Denunciar

0

You could use a recursive generator:

function* iterPerms(arr, n, first=0) {
    if (n > arr.length - first) return;
    if (n === 0) return yield [];
    for (const res of iterPerms(arr, n - 1, first + 1)) yield [arr[first], ...res];
    yield* iterPerms(arr, n, first + 1);
}

const arr = [1, 4, 5, 8];
for (let perm of iterPerms(arr, 3)) console.log(...perm);

To convert the generator to a normal function that returns a nested array, do:

const getNPermutate = (arr, n) => Array.from(iterPerms(arr, n));
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