Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

74
Vistas
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.

7 months ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.