I have list of ages and agesGroups
I want to take each element of the list ages and search in list ageGroup the interval where it is to recover the price ,If an element is in two interval so we recover the lowest price of the list ,I want the sum of the total prices.
For example :
for age 8 I have price =50 and for 20 and 67 i have two choices 90 and 70 ,I will choose the lowest price which is 70 and then the result have to be 70 70 50 = 190 price = 190
let ages = [8, 20, 67]
let agesGroups = [{
min: 10,
max: 90,
price: 90
},
{
min: 10,
max: 90,
price: 70
},
{
min: 0,
max: 10,
price: 50
}
]
let price = 0
ages.forEach(a => {
agesGroups.forEach(s => {
if (a >= s.min && a <= s.max) {
price = price parseInt(s.price, 10);
}
})
})
console.log(price);
The result that i got
price = 140
CodePudding user response:
Sometimes using Array methods are to restrictive of what's returned and it's difficult to navigate. A for...of loop is easier to read and refactor with Array methods later.
Define
pricesarray to keep each best priceOuter
for...ofloop to iterateagesarrayDefine
inRangearray to keep each price within arangeInner
for...ofloop to iteraterangesarray- Determine if
ageis within range ofrange.minandrange.max - Push
range.priceintoinRangearray ifageis within range
- Determine if
Push the smallest
range.priceofinRangeintopricesarrayprices.push( Math.min(...inRange));
Then add all prices of
pricearrayprices.reduce((sum, add) => sum add)
let ages=[8,20,67],ranges=[{min:10,max:90,price:90},{min:10,max:90,price:70},{min:0,max:10,price:50}];
let prices = [];
for (let age of ages) {
let inRange = [];
for (let range of ranges) {
if (age >= range.min && age <= range.max) {
inRange.push(range.price);
}
}
prices.push( Math.min(...inRange));
}
let total = prices.reduce((sum, add) => sum add);
console.log(total);
Refactored
let ages=[8,20,67],ranges=[{min:10,max:90,price:90},{min:10,max:90,price:70},{min:0,max:10,price:50}];
let total = ages.map(age => {
let prices = ranges.flatMap(rng => rng.min <= age && rng.max >= age ? [rng.price] : []);
return Math.min(...prices);
}).reduce((sum, add) => sum add);
console.log(total)
CodePudding user response:
Solution - by the suggestion of @Barmar - using reduce(). "result" now contains minimal prices for all the ages. You can summarize them if need:
let result = []
ages.forEach(a => {
result.push(agesGroups.reduce((res, s) => {
if(a >= s.min && a <= s.max) {
if (s.price < res) { res = s.price}
}
return res
}, Infinity));
});
console.log(result)
