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

153
Views
Empuje una matriz de objetos que componen una cuenta de 100

Tengo una matriz de objetos como el siguiente:

 const items = [ { 'name': 'P1', 'value': 50 }, { 'name': 'P1', 'value': 49 }, { 'name': 'P2', 'value': 50 }, { 'name': 'P3', 'value': 50 } ]

Necesito sumar los valores y luego ingresar a una matriz de objetos solo si 1 o más objetos conforman un value total de 100.

Rendimiento esperado:

 const groupedItems = [ [ { 'name': 'P1', 'value': 50 }, { 'name': 'P1', 'value': 49 }, ], [ { 'name': 'P2', 'value': 50 }, { 'name': 'P3', 'value': 50 } ] ]

Lo que he probado:

 const temp = []; for (var i = 0; i < items.length; i++) { if ((items[i] + items[i + 1]) < 100) { temp.push(items[i]); } } groupedItems.push(temp);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Supongo que me acercaría a su solución de esta manera:

Cada vez que recupera la primera matriz, la reduce y si the sum of the array + the value of your item es inferior a 100 , empuja su elemento en la matriz.

De lo contrario, empujando una nueva matriz en sus groupedItems que contiene su elemento.

Puede haber una mejor manera de hacer esto, pero esta es la idea principal.

 const items = [{ 'name': 'P1', 'value': 50 }, { 'name': 'P1', 'value': 49 }, { 'name': 'P2', 'value': 50 }, { 'name': 'P3', 'value': 50 } ] const groupedItems = [] items.forEach(item => { if (groupedItems.length > 0) { const lastArray = groupedItems[groupedItems.length - 1] const sumLastArray = lastArray.reduce((total, current) => current.value + total, 0) if (sumLastArray + item.value < 100) { lastArray.push(item) } else { groupedItems.push([item]) } } else { groupedItems.push([item]) } }) console.log(groupedItems)

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!