how can i get forEach elements lengths which was checked in my if else statement?
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);
also i want to push with same travellerAgeRangeId only once but it is pushing twice.
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} ]
Updated
Although your approach is inappropriate for doing this but somehow i solved your problem; DEMO
Globally declare your variable
infant = 0;
child = 0;
adult = 0;
Suppose you have array of ages like this
this.ages = [18, 20, 1, 11, 12, 0.2, 10];
Now you run a for loop to count infants, children, and adults.
for (let a = 0; a <= this.ages.length; a++) {
if (a >= 0 && a <= 1) {
this.infant = this.infant + 1;
} else if (a >= 2 && a <= 11) {
this.child = this.child + 1;
} else if (a >= 12 && a <= 59) {
this.adult = this.adult + 1;
}
}
and when running the foreach loop you can then reference your global variable like this:
this.ages.forEach((a) => {
//infant
if (a >= 0 && a <= 1) {
this.id = 1;
this.travel.listOfTravellerCountPerAgeRange.push({
travellerAgeRangeId: this.id,
travellerCount: this.infant,
});
}
//child
else if (a >= 2 && a <= 11) {
this.id = 2;
this.travel.listOfTravellerCountPerAgeRange.push({
travellerAgeRangeId: this.id,
travellerCount: this.child,
});
}
//adult
else if (a >= 12 && a <= 59) {
this.id = 3;
this.travel.listOfTravellerCountPerAgeRange.push({
travellerAgeRangeId: this.id,
travellerCount: this.adult,
});
}
});
Old Version
you are pushing element length in your travellerCount property which is not an array
All you need is get this.ages length
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: this.ages.length,
});
}
//adult
else if (a >= 12 && a <= 59) {
this.id = 3;
this.travel.listOfTravellerCountPerAgeRange.push({
travellerAgeRangeId: this.id,
travellerCount: this.ages.length,
});
}
});
console.log(this.travel);