Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find min and max using reduce but with extra condition

I manage to find min and max in an array of object, but in the same time I have to include other variables. I have extra special_min_price and special_max_price, how can I include them in reduce method?

const price = [
{min_price:100, max_price:200},
{min_price:70, max_price:200},
{min_price:50, max_price:100},
{min_price:100, max_price:400},
{min_price:120, max_price:600},
],
special_min_price = 40,
special_max_price = 800;

let x = _.reduce(price, function(a, b) {
            a.min_price = Math.min(a.min_price, b.min_price);
            a.max_price = Math.max(a.max_price, b.max_price);
            return a
        });
like image 993
Giala Jefferson Avatar asked Dec 03 '25 21:12

Giala Jefferson


1 Answers

I assumed you wanted the special prices to be a part of that reduce. If that's the case, then you could try adding a step before your reduce where you add on to the list of prices. I imagine it would look something like this:

const price = [
{min_price:100, max_price:200},
{min_price:70, max_price:200},
{min_price:50, max_price:100},
{min_price:100, max_price:400},
{min_price:120, max_price:600},
],
special_min_price = 40,
special_max_price = 800;

let x = _.chain(price)
         .concat({min_price:special_min_price,
             max_price:special_max_price})
         .reduce(function(a, b) {
             a.min_price = Math.min(a.min_price, b.min_price);
             a.max_price = Math.max(a.max_price, b.max_price);
             return a
         })
         .value();
like image 163
Stucco Avatar answered Dec 06 '25 11:12

Stucco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!