简体   繁体   中英

I have an array of objects. Each object contains max and min key value pairs. How do I find the object that contains a predefined value?

I have an array of insurance rates that looks like this

const insuranceRate = [
{
    "min_value": 1,
    "max_value": 25000,
    "add": 328
}, {
    "min_value": 25001,
    "max_value": 25500,
    "add": 331
}, {
    "min_value": 25501,
    "max_value": 26000,
    "add": 335
}, {
    "min_value": 26001,
    "max_value": 26500,
    "add": 338
}]

Let's say I purchase a car at $25,900. How to I find the right object and add $335 to my insurance cost?

Thats pretty simple, have an for loop go through every element and check if ur value is inbetween the min and max values the function would look something like that:

function F(value){
    for( i=0;i<insuranceRate.length;i++){
        if ( value >= insuranceRate[i].min_value  && value <= insuranceRate[i].max_value){
            return insuranceRate[i];
        }
    }
    return -1;
}

which returns the element within the range, which u then can use to get your add value, also if ur value is not between the range, it'll return -1

If you want the one with the lowest price I'd go with this:

var valid_rates = []; 
insuranceRate.forEach((item, index)=>{ 
    if (price >= item.min_value &&  price <= item.max_value) { 
        valid_rates.push(item.add) ;
    }
}) ;

// Lowest price
Math.min(valid_rates) ;

Loop over the aray and check whether your car cost is in the range, if so - add it to the insurance cost - in this example I initialized it with 0:

var my_car = 25900;
var insuranceCost = 0;
for (var i=0; i<insuranceRate.length; i++) {
    if (my_car >= insuranceRate[i].min_value && 
        my_car <= insuranceRate[i].max_value) {
           insuranceCost += insuranceRate[i].add;
    }
} 

console.log(insuranceCost); //335

Here you go

 const insuranceRate = [
   {
    "min_value": 1,
    "max_value": 25000,
    "add": 328
   }, {
    "min_value": 25001,
    "max_value": 25500,
    "add": 331
   }, {
    "min_value": 25501,
    "max_value": 26000,
    "add": 335
   }, {
    "min_value": 26001,
    "max_value": 26500,
    "add": 338
   }];
   var price=25900;

   var filter=insuranceRate.filter(i=>price >= i.min_value && price <= 
   i.max_value);
   console.log("Result:",filter);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM