Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

111
Vistas
if else statement inside forEach

i have array of ages, i want to know in what age range are those ages and how many, and then push into my object.

issue i have is that if there is more then 1 age in the same range it pushes twice, i want to push it once and display length of it, but it returns undefiened

here is my 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);

output i get from console.log is:

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

output i wanna get:

 listOfTravellerCountPerAgeRange: [  
 {travellerAgeRangeId: 3, travellerCount: 2}, 
 {travellerAgeRangeId: 1, travellerCount: 1} ]
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

If you want to count some value from the array items, you should use reduce method:

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);

I didn't run that code, but it should work =)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda