user16405978
user16405978

Reputation:

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} ]

Upvotes: 0

Views: 480

Answers (1)

konclave
konclave

Reputation: 678

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

Upvotes: 1

Related Questions