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

119
Views
¿Por qué no se devolverá el último valor de matriz?

Tengo una matriz con varios valores y quiero obtener un valor almacenado en el múltiplo de 3. Entonces, en este caso, la nueva matriz debería ser 13 y 28 . Sin embargo, solo obtengo 13 .

Código:

 // array1 --> [ '5', '10', '13', '15', '20', '28' ] var trueLength = array1.length; var iCount = 1; for(var i = 0; i < trueLength;) { if(iCount % 3 != 0) { array1.shift(); } else if (iCount % 3 == 0) { array2.push(array1[i]); array1.shift(); } iCount += 1; if(iCount == trueLength) break; }

Producción:

 [ '13' ]

No veo nada lógicamente incorrecto para que solo genere 13 , lo que no tiene sentido.

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

0

array1.shift(); eliminará el primer elemento de la matriz. Si hace esto mientras itera sobre iCount , se saltará algunos elementos de la matriz, ya que está eliminando elementos e incrementando el índice que se está iterando.

Simplemente filtre la matriz por el módulo del índice que se está iterando.

 const arr = [ '5', '10', '13', '15', '20', '28' ]; const result = arr.filter((_, i) => i % 3 === 2); console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

tienes un pequeño problema lógico en la condición de break , esto sería suficiente

 var array1 = ['5', '10', '13', '15', '20', '28']; var array2 =[]; var trueLength = array1.length; var iCount = 1; for(var i = 0; i < trueLength;) { if(iCount % 3 != 0) { array1.shift(); } else if (iCount % 3 == 0) { console.log(iCount); array2.push(array1[i]); array1.shift(); } iCount += 1; if(iCount == trueLength+1) break; } console.log(array2[1]);
about 4 years ago · Juan Pablo Isaza Report

0

Si le gusta usar el patrón de cambio y empujar el valor necesario, puede usar dos variables para realizar un seguimiento de la longitud de los elementos restantes y otra para calcular el resto.

 const array = ['5', '10', '13', '15', '20', '28']; let i = 1, l = array.length; while (l) { const value = array.shift(); if (i % 3 === 0) array.push(value); l--; i++; } console.log(array);

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!