I have an array of ages and I want to determine the age range for each age along with the count, then push it into my object.
The issue I am facing is that if there are multiple ages in the same range, it gets pushed twice. I only want to push it once and display the length, but it returns undefined.
Here is the code on StackBlitz
this.ages = [18, 20, 1];
this.ages.forEach((age) => {
// Infant
if (age >= 0 && age <= 1) {
this.id = 1;
this.travel.listOfTravellerCountPerAgeRange.push({
travellerAgeRangeId: this.id,
travellerCount: age.length,
});
}
// Adult
else if (age >= 12 && age <= 59) {
this.id = 3;
this.travel.listOfTravellerCountPerAgeRange.push({
travellerAgeRangeId: this.id,
travellerCount: age.length,
});
}
});
console.log(this.travel);
The output displayed from console.log is:
listOfTravellerCountPerAgeRange: [
{travellerAgeRangeId: 3, travellerCount: undefined},
{travellerAgeRangeId: 3, travellerCount: undefined},
{travellerAgeRangeId: 1, travellerCount: undefined} ]
The desired output I hope to achieve is:
listOfTravellerCountPerAgeRange: [
{travellerAgeRangeId: 3, travellerCount: 2},
{travellerAgeRangeId: 1, travellerCount: 1} ]