Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
Parece que no puedo identificar el problema (dividir una matriz en partes)

Entonces, se supone que esta función divide la matriz en partes del tamaño del segundo argumento, por ejemplo, [1, 2, 3, 4] con el segundo argumento 2 devolvería [[1, 2], [3, 4]], si el número es 3 devolvería [[1, 2, 3], [4]] y así sucesivamente. Mi función parece comportarse de manera similar, pero solo devuelve el primer fragmento, y los fragmentos posteriores son solo matrices vacías. Aumento el índice por el segundo argumento después de cada iteración, por lo que no estoy seguro de por qué no funciona. ¿Alguien puede explicar qué está sucediendo exactamente aquí y dónde está el error en la lógica?

 let arr = [1, 2, 3, 4, 5, 6] function test(arr, num) { let idx = 0; let newArr = [] while (idx < arr.length) { newArr.push(arr.slice(idx, num)) idx = idx + num } return newArr } console.log(test(arr, 2))

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Necesita un índice como segundo parámetro de Array#slice , en lugar de la longitud del segmento.

Por ejemplo, si toma la segunda matriz, index = 2 y el segundo parámetro tiene que ser 4 , el índice del final para el corte.

 chunks values 1 2 3 4 5 6 indices 0 1 2 3 4 5 slice 0 2 1 2 2 4 3 4 4 6 5 6 

 function test(arr, num) { let idx = 0; let newArr = []; while (idx < arr.length) { newArr.push(arr.slice(idx, idx += num)); } return newArr; } let arr = [1, 2, 3, 4, 5, 6]; console.log(test(arr, 2));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!