I possess a collection of objects, where each object is composed of maximum and minimum key-value pairs. What is the method to determine which object includes a specified value within it?

I have a list of insurance rates structured 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
}]

If I buy a vehicle priced at $25,900, how can I identify the correct object and increase my insurance cost by $335?

Answer №1

Here is the requested code snippet:


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);

Answer №2

It's quite straightforward. Just create a for loop to iterate through each element and check if your value falls within the min and max values. The function would look something like this:

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

This function will return the element within the specified range, which you can then use to retrieve the corresponding value. If the value is not within the range, it will return -1.

Answer №3

If you are aiming for the most budget-friendly option, I suggest going with this recommendation:

var affordable_options = []; 
insuranceRate.forEach((option, idx)=>{ 
    if (price >= option.min_value &&  price <= option.max_value) { 
        affordable_options.push(option.add) ;
    }
}) ;

// Lowest priced option
Math.min(affordable_options) ;

Answer №4

Go through the array to verify if your vehicle's price falls within a certain range, and if it does, include it in the insurance cost - which is initialized at 0 in this case:

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

console.log(insuranceCost); //335

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble triggering a change event within a React component?

I'm working on a straightforward react-component that consists of a form. Within this form, the user can search for other users. To ensure the form is valid, there needs to be between 3 and 6 users added. To achieve this, I've included a hidden ...

Transforming the output from a processor into an array structure

Being a newcomer in the field of development, I have a question about how to retrieve data based on my requirements and what is considered the best practice? This is the structure of my design: JavaScript (Ajax call) >> ashx handler (Access databa ...

Exploring Angular 2: Unveiling the secrets of lifecycle hooks in lazy loaded

Currently, I'm working on an application that involves lazy loaded Angular modules. I have a straightforward inquiry: Is there a way to detect an event once a module is loaded? For instance, similar to the OnInit lifecycle hook for components. I fo ...

Utilizing module.exports and ES6 for exporting imports

I am currently facing an issue trying to import a function into a file and then export it from that file. It seems like a fairly straightforward task, but for some reason I am having trouble getting it to work. search_action.js function search_actions() ...

Guide to emphasize the active navigation tab in a particular scenario

Utilizing this template for JavaScript to choose the appropriate navigation using JQuery, with reference to this API. Snippet of my current code: index.php <html> <head> <title>ChillSpot Alpha 1.2.3</title> &l ...

What is the method for determining if a given point falls within a 3-dimensional cube?

I am currently seeking a method to determine whether a location is situated inside a rotated cube. To provide some context, I have access to the coordinates (x,y,z), rotation values (x,y,z), and dimensions (x,y,z). I am working with Javascript for this pr ...

Error Encountered During Serialization with ASP.Net AJAX and JavaScript

Encountered an error message stating "Out of Stack Space" while attempting to serialize an ASP.Net AJAX Array object. Below is a breakdown of the issue with simplified code: Default.aspx MainScript.js function getObject(){ return new Array(); } ...

Tips for integrating three-dimensional JSON models from ThreeJS into A-frame

Looking to incorporate some low poly models from into a ThreeJS JSON model in A-frame. This method is preferred due to its efficiency and smaller file size, resulting in faster loading times. However, there seems to be a lack of guidance on how to achieve ...

What is preventing me from being able to use object spread results in TypeScript casting?

Uniqueness in Question My inquiry was not aimed at identifying the type or class name of an object. Rather, it delved into the concept of "casting" an object to a specific type, which arose from a misconception about TypeScript and its functionality. This ...

Transfer an HTML file object between two <input type="file"> elements

I am looking to integrate a multi-file uploader into a form that allows users to prioritize the files they upload using draggable and sortable jQuery tools. One way I have added a multi-file input is: <input type = "file" multiple> When I select m ...

Coffeescript does not allow setting the AngularJS controller property as the last line of code

Having an issue while using Coffeescript to define a controller with the "HomeController as homeCtrl" syntax. angular.module('myApp.controllers',[]).controller("HomeController", -> @someArray = [] # return ) Encountering a problem ...

Execute a PUT request within a Firebase Cloud Function database handler

I am working on syncing data between my server's database and Firebase realtime db. The first part, which involves syncing from my server to Firebase, is already complete. However, I am facing challenges with the second part - syncing data from Fireba ...

Creating new 'morphing' geometry in Three.js with all required buffers: A step-by-step guide

I have implemented a web-worker to load a .json file that contains an animated 3D model. To optimize performance, I am transferring Float32Array buffers for the main arrays (vertices, normals, etc.) back to the UI thread, leveraging the benefits of transfe ...

changing the css transformation into zoom and positioning

My goal is to incorporate pinch zoom and panning using hardware-accelerated CSS properties like transform: translate3d() scale3d(). After completing the gesture, I reset the transform and switch to CSS zoom along with absolute positioning. This method ensu ...

locomotory mesh decentralized sorting

I am attempting to implement in-browser sorting for my flexigrid. Currently, the grid is displaying data from a static XML file exactly how I want it, but the table itself does not sort because it is working off of local data. While researching solutions, ...

What is the best way to structure an array containing various data types?

Greetings, I am a beginner in Java and currently trying to understand how to store this data in a 6-row, 3-column array. x1 John 6 x2 Smith 9 x3 Alex 7 y1 Peter 8 y2 Frank 9 y3 Andy 4 Later on, I plan to extract the numbers from the last column for some ...

Ways to revert to the initial state in React.js

Check out my codeSandbox project here: https://codesandbox.io/s/bold-lederberg-d2h508?file=/src/Components/Products/Products.js I'm having trouble getting the items back to their original presentation when clicking on "default" - sorting by price wor ...

Encountering issue in Angular 2 unit test: Error message states that 'subscribe' is not a property of undefined

I am currently focused on writing Jasmine unit tests for my Angular 2 application. it('ensure object passed to cancellation service is in correct format for cancel contract transaction', () => { var cancelReason = new models.CancelReason( ...

Filtering Typeahead results based on multiple fields in Angular

My typeahead feature currently filters based on a person's name only. However, my person object contains additional fields such as surname, and I would like the filter to work based on both name and surname. Here is the existing typeahead code using ...

Issues with displaying images in Fancybox

I've integrated FancyBox into my website, but I'm experiencing a minor issue. While the FancyBox works perfectly in Dreamweaver, it seems to malfunction in various browsers. As someone who is not well-versed in programming, I'm struggling t ...