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

126
Views
Inserte un elemento en un índice específico dentro de la matriz que se está repitiendo

¿Cuál es la mejor manera de actualizar una matriz insertando el nuevo elemento en un índice específico cuando se cumple cierta condición durante el bucle?

 const exampleArray = [ {item: 1, count: 5}, {item: 2, count: 20}, {item: 3, count: 10}, {item: 6, count: 9} {item: 4, count: 5}]

Quiero hacer un bucle de exampleArray mientras hago un seguimiento del conteo e inserto un nuevo elemento justo después cuando el conteo es mayor o igual a 10 y luego restablezco el conteo a 0 para el siguiente ciclo

entonces el resultado que quiero es

 const resultArray = [ {item: 1, count: 5}, {item: 2, count: 20}, {item: 'new item 1 as count is over 10', count: 0}, {item: 3, count: 10}, {item: 'new item 2 as count is equal to 10', count: 0}, {item: 6, count: 9}, {item: 4, count: 5}, {item: 'new item 3 as count is > 10, previous two counts (9 + 5 )', count: 0 }]

probé esto

 let count = 0 exampleArray.forEach((item, index) => { count += item.count if(count >= 10) { exampleArray.splice(index + 1, 0, {item: 'item to be added', count: 0} count = 0 } })
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Ambos crean una nueva matriz: si desea sobrescribir, use let y asigne de nuevo al original

TJ Mapa sugerido y plano - eso es un planoMapa

 const exampleArray = [ {item: 1, count: 5}, {item: 2, count: 20}, {item: 3, count: 10}, {item: 4, count: 5}]; let count = 0; const resultArray = exampleArray.flatMap(item => { count += item.count; if (count >= 10) { count = 0 return [item, {item:"new", count:0}] } return item; }); console.log(resultArray);

Reducir

 const exampleArray = [ {item: 1, count: 5}, {item: 2, count: 20}, {item: 3, count: 10}, {item: 4, count: 5}]; let count = 0; const resultArray = exampleArray.reduce((acc,cur) => { count += cur.count; acc.push(cur); if (count >= 10) { count = 0 acc.push({item:"new", count:0}) } return acc; },[]); console.log(resultArray);

about 4 years ago · Juan Pablo Isaza Report

0

Yo optaría por un bucle for o for...of simple. Si está feliz de crear una nueva matriz (si no, veo que no está en su pregunta, vea a continuación):

 const result = []; for (const item of exampleArray) { count += item.count; result.push(item); if (count >= 10) { result.push({item: 'item to be added', count: 0}); } }

o (originalmente usé map ... flat() , porque me olvidé nuevamente de flatMap ; mplungjan me lo recordó ) :

 let count = 0; const result = exampleArray.flatMap(item => { count += item.count; if (count >= 10) { return [item, {item: 'item to be added', count: 0}]; } return item; });

Ejemplo en vivo:

 const exampleArray = [ {item: 1, count: 5}, {item: 2, count: 20}, {item: 3, count: 10}, {item: 4, count: 5} ]; let count = 0; const result = []; for (const item of exampleArray) { count += item.count; result.push(item); if (count >= 10) { result.push({item: 'item to be added', count: 0}); } } console.log(result); count = 0; const result2 = exampleArray.map(item => { count += item.count; if (count >= 10) { return [item, {item: 'item to be added', count: 0}]; } return item; }).flat(); console.log(result2);

Si realmente desea modificar la matriz existente, el bucle for le permite controlar la variable de índice:

 for (let index = 0; index < exampleArray.length; ++index) { const item = exampleArray[index]; count += item.count; if (count >= 10) { exampleArray.splice(index + 1, 0, {item: 'item to be added', count: 0}); count = 0; ++index; // Skip the item we just added } }

Ejemplo en vivo:

 const exampleArray = [ {item: 1, count: 5}, {item: 2, count: 20}, {item: 3, count: 10}, {item: 4, count: 5} ]; let count = 0; for (let index = 0; index < exampleArray.length; ++index) { const item = exampleArray[index]; count += item.count; if (count >= 10) { exampleArray.splice(index + 1, 0, {item: 'item to be added', count: 0}); count = 0; ++index; // Skip the item we just added } } console.log(exampleArray);

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!