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

135
Visualizações
How to reconstruct an array in a specific format using a loop in typescript?

I have an array like this

animals = [Dog,Cat,Mouse,Tiger,Lion,Bird,Horse]

I want to break it and display this array in the below format

0: [Dog,Cat,Mouse]
1: [Tiger,Lion,Bird]
2: [Horse]

For that I have written a function like this

splitPairs(arr) {
      var pairs = [];
      for (var i=0 ; i<arr.length ; i+=3) {
        if (arr[i+1] !== undefined && arr[i+2] !== undefined) {
          pairs.push ([arr[i], arr[i+1], arr[i+2]]);
        } else if(arr[i+1] !== undefined) {
          pairs.push ([arr[i], arr[i+1]]);
        } else {
          pairs.push ([arr[i]]);
        }
}
this.animals = pairs;

When I'm using splitPairs(animals) function everything is working fine.

BUT THE PROBLEM IS

I dont know that breakup count (which is in this case is 3)

Suppose that animal array will break after 5 or say 10 then how to use that function with a loop so that it will break automatically.

Say splitPairs(animals, 5) I pass 5 in the second parameter and it will break automatically after 5th index.

I hope I make you understand my problem.

Any kind of help would be highly appreciated.

about 4 years ago · Juan Pablo Isaza
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