Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

87
Visualizações
Split a two-dimensional array of specified length

Split the original array into a two-dimensional array of the specified length

list => source array

columns => columns number

targetList => two-dimensional array

const list = [1,2,3,4,5,6,7,8,9,10]
const columns = 4;
const targetList = [ [1,2,3], [4,5,6], [7,8,9], [10] ];

const columns = 5;
const targetList = [ [1,2], [3,4], [5,6], [7,8], [9,10] ];

const columns = 6;
const targetList = [ [1,2], [3,4], [5,6], [7,8], [9], [10] ];
const list = [1,2,3,4,5,6]
const columns = 4;
const targetList = [ [1,2], [3,4], [5], [6] ];
const list = [1,2,3,4]
const columns = 5;
const targetList = [ [1], [2], [3], [4] ];
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use Array.prototype.reduce and transform the given list to the desired grid.

Push the a new row to the resultant grid if any of the following conditions meet:

  1. If there are no rows currently.
  2. If the last row is filled i.e. no more columns can be added to the last row, then add a new row with the current item.
  3. If items remaining to be pushed becomes equal to rows remaining to be created.

const transform = (list, rows) =>
  list.reduce((t, l, i) => {
    if (
      !t.length ||
      t.at(-1).length >= Math.ceil(list.length / rows) ||
      list.length - i === rows - t.length
    ) {
      t.push([]);
    }
    t.at(-1).push(l);
    return t;
  }, []);

console.log(transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 4));
console.log(transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5));
console.log(transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 6));
console.log(transform([1, 2, 3, 4, 5, 6], 4));
console.log(transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 4));
console.log(transform([1, 2, 3, 4], 5));

Other relevant documentations:

  • Array.prototype.at
  • Array.prototype.push
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda