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

113
Views
declaración if else dentro de forEach

tengo una variedad de edades, quiero saber en qué rango de edad están esas edades y cuántas, y luego presionar en mi objeto.

el problema que tengo es que si hay más de 1 edad en el mismo rango, presiona dos veces, quiero presionarlo una vez y mostrar su duración, pero regresa sin definir

aquí está mi stackblitz

 this.ages = [18, 20, 1]; this.ages.forEach((a) => { //infant if (a >= 0 && a <= 1) { this.id = 1; this.travel.listOfTravellerCountPerAgeRange.push({ travellerAgeRangeId: this.id, travellerCount: a.length, }); } //adult else if (a >= 12 && a <= 59) { this.id = 3; this.travel.listOfTravellerCountPerAgeRange.push({ travellerAgeRangeId: this.id, travellerCount: a.length, }); } }); console.log(this.travel);

la salida que obtengo de console.log es:

 listOfTravellerCountPerAgeRange: [ {travellerAgeRangeId: 3, travellerCount: undefined}, {travellerAgeRangeId: 3, travellerCount: undefined}, {travellerAgeRangeId: 1, travellerCount: undefined} ]

Salida que quiero obtener:

 listOfTravellerCountPerAgeRange: [ {travellerAgeRangeId: 3, travellerCount: 2}, {travellerAgeRangeId: 1, travellerCount: 1} ]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Si desea contar algún valor de los elementos de la matriz, debe usar el método de reduce :

 this.travel = {}; this.ages = [1,1,45]; this.travel.listOfTravellerCountPerAgeRange = this.ages.reduce((acc, a) => { let id if (a >= 0 && a <= 1) { id = 1; } else if (a >= 12 && a <= 59) { id = 3; } const record = acc.find((entry) => entry.travellerAgeRangeId === id); if (record) { record.travellerCount += 1; } else { acc.push({travellerAgeRangeId: id, travellerCount: 1}); } return acc; }, []); console.log(this.travel.listOfTravellerCountPerAgeRange);

No ejecuté ese código, pero debería funcionar =)

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!