Obtain the closest numerical range using JavaScript

I have a range object and an array of price values. My goal is to find the nearest range from the range object for each value in the price values array. I attempted the solution below, but it did not give me the correct range.

range = {
    0: '25-500',
    1: '1500-2500',
    2: '5000-10000'
}

let price_values = [5, 100, 1500, 7000, 15000]

Here is my attempted solution

    let nearestPriceRangeArr = [];
let rangeLength = Object.keys(range).length;
Object.keys(range).forEach(key => {
    price_values.forEach((price, qKey) => {
        let rangeArr = key.split("-");
        let fromRange = parseInt(rangeArr[0]);
        let toRange = parseInt(rangeArr[1]);
        if(price <= fromRange) {
            if(x == 0) {
                nearestPriceRangeArr[price] = key;
            }
        } else {
            if (price >= fromRange && price <= toRange) {
                nearestPriceRangeArr[price] = key;
            } else {
                if(price >= toRange) {
                let ab = (x == rangeLength - 1) ? key : key;
                    nearestPriceRangeArr[price] = ab;
                }
            }
        }
        x++;
    });
});

Expected Result

nearestPriceRangeArr[5] = '25-500';
nearestPriceRangeArr[100] = '25-500';
nearestPriceRangeArr[1500] = '1500-2500';
nearestPriceRangeArr[7000] = '5000-10000';
nearestPriceRangeArr[15000] = '5000-10000';

Answer №1

If you have an array of price ranges, you can determine the appropriate range by comparing the price.

const
    customRange = ['25-500', '1500-2500', '5000-10000'],
    pricesToCheck = [5, 100, 1500, 7000, 15000],
    finalResult = Object.fromEntries(pricesToCheck.map(price => [price, customRange.find((range, index, { length }) => {
        const [minPrice, maxPrice] = range.split('-').map(Number);
        return price <= maxPrice || index === length - 1;
    })]));

console.log(finalResult);

Answer №2

Not sure what caused it, but here's a unique solution to your unusual problem.

console.clear();
let range = {
    0: '25-500',
    1: '1500-2500',
    2: '5000-10000'
}
let price_values = [5, 100, 1500, 7000, 15000];
let nearestPriceRangeArr = {};
let rangeValues = Object.values(range);

price_values.forEach((price)=>{
  // for prices which are in one the range_values
  rangeValues.forEach((range, rangeIndex)=>{
    let ranges = range.split('-');
    if(price >= parseInt(ranges[0]) && price <= parseInt(ranges[1])){
      nearestPriceRangeArr = {
        ...nearestPriceRangeArr,
       [price] : range
      }
    }
    /* if price is not falling in any range */
    // if price is smaller than first range
    if(rangeIndex === 0){
        if(price <= ranges[0]){
          nearestPriceRangeArr = {
          ...nearestPriceRangeArr,
         [price] : range
        }
      }
    } else {
      // if price is greater than previous range
      // and smaller than current range
      const previousRanges = rangeValues[rangeIndex - 1].split("-");
      if(price > previousRanges[1] && price <= ranges[0] ){
         nearestPriceRangeArr = {
          ...nearestPriceRangeArr,
         [price] : range
        }
      } else {
        // if price is greater than last range
        if(price > ranges[1]){
            nearestPriceRangeArr = {
            ...nearestPriceRangeArr,
           [price] : range
          }
        }
      }
    }
  })  
})

console.log(nearestPriceRangeArr);
console.log(nearestPriceRangeArr[5])
console.log(nearestPriceRangeArr[100])
console.log(nearestPriceRangeArr[1500])
console.log(nearestPriceRangeArr[7000])
console.log(nearestPriceRangeArr[15000])

https://i.sstatic.net/UZyLi.png

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

Typescript provides the flexibility to construct incomplete or partially valid objects

My attempt to create a partial helper function in Typescript led me to an incorrect version that went unnoticed by Typescript: Typescript version: 5.2.2 type A = { a: number; b: string }; // incorrect const buildPartialBad = (key: keyof A, val: A[keyof A ...

Efficient segmentation of text using CSS and JavaScript

Currently, I'm involved in a project that allows users to create their own timelines with events. However, there seems to be an issue with the event titles. Users are able to create events with extremely long titles, such as: `1231231231231231231231 ...

Setting the z-index for a JavaScript plugin

I need help with embedding the LinkedIn plugin into a website that has stacked images using z-index for layout. I have tried assigning the plugin to a CSS class with a z-index and position properties, but it hasn't worked as expected. Can anyone sugge ...

Is it not possible to utilize inline "if" statements in conjunction with useEffect within a functional React component?

I'm currently working on integrating Okta's React SDK into a TypeScript-based application using functional components instead of class-based ones. My main challenge lies in rendering a part of the app's menu based on the user's authenti ...

Is it true that TypeScript prohibits the presence of circular references under the condition of having generic parameters

I encountered an issue of type error in the given code snippet Type alias 'bar2' circularly references itself.ts(2456) type foo = { bars: bar[]; }; //works fine type bar = foo; type foo2<T extends Record<string, unknown> = Record< ...

Exporting a JavaScript chart to an Excel file using Highcharts

Trying to export a JavaScript chart (HighCharts) into an Excel file has been challenging. The chart, rendered in a div, does not carry over the HTML and CSS formatting that the JavaScript generates, resulting in plain text without style. I have attempted ...

Tips for arranging alternating elements in a column layout using an array data model

In the $scope there is a dynamic array and in the HTML template, there are three columns. The goal is to render elements from the array in the HTML like this: <div class="first-column"> <div><!--element of (index + 3) % 3 === 0 will be pl ...

What is the most efficient method of converting an object into a list without resorting to a double for loop?

Within my code, there is an object named 'times' which contains another object labeled '20102'. This inner object has a collection of three sub-objects structured like so: times: { 20102: [ { name:'jane', age:12 }, ...

Error: Trying to modify an immutable property 'title' of object '#<Object>' - React JS and Typescript

Whenever I press the Add button, all input values are stored in a reducer. However, if I append any character to the existing value in the input fields, it triggers the following error: Cannot assign to read only property 'title' of object &apos ...

Can jQuery be used to edit an XML file?

Can XML files be updated using jQuery, or is server-side scripting necessary for this task? Thank you ...

Receiving an abundance of alert notifications triggered by the search functionality of jsTree

I've created a function to search for text within the jsTree framework. The goal is to highlight the node if the search text is found. If not, inform the user with a message saying "No node matching the search string, please try again." However, I&a ...

What is the method to update reference models in mongodb by generating documents within a different model?

In my API, I have three models: Patient, Doctor, and Reviews. The Reviews model is referenced in the Doctor model, with the intention that a patient can post a review for a specific doctor using Review.create(). However, even after the review document is c ...

What is the best way to retrieve information from a database using JSON with PHP, JQUERY, and

Trying to retrieve data from a MySQL database and pass it to a JavaScript file has been quite a challenge. Despite searching extensively online, the examples I found didn't work in my specific scenario. .html file <!DOCTYPE html PUBLIC '-//W ...

discovering the absence of any letters within an array

Looking for a way to find multiple missing letters in an array? Check out this code snippet: function missingLetters(str) { var nums = str.split('').map(function(letter){ return letter.charCodeAt(); }) var result = []; for(va ...

Struggles with toggling a sliding menu using JQuery

As I work on constructing a menu, I've implemented submenus that slide down upon hovering over the parent item and remain expanded when clicking on an arrow next to the parent. While the hovering functionality is working correctly, I'm encounteri ...

Utilizing Socket IO and Node JS to stream audio from a microphone via sockets

I am currently developing an app that requires users to use their phone's microphone to communicate with each other in the game lobby. However, I have encountered several challenges along the way. My approach involves using Node JS socket io and sock ...

Mastering the art of utilizing Context API and Provider for optimal functionality

Currently, I am working on implementing a dark mode feature in my project. Despite everything appearing to be set up correctly, it seems like the Context at App is not re-rendering when I use the setTheme function inside the Provider. Can someone help me t ...

Ways to merge several getServerSideProps functions

Within my project, I have two important pages: index.js and other.js. In index.js, there exists a crucial method known as getServerSideProps: export async function getServerSideProps(context) { //code here } The challenge arises when I realize that I ...

Fastblox - utilizing javascript SDK for group chatting

I've been facing issues setting up a group chat using QB Javascript SDK. There are a few problems I am encountering: Firstly, I consistently receive a "room is locked" message. Here's the link to the screenshot: https://i.sstatic.net/auR21.png. ...

The Angular $rootScope.user.userMessage throws an error stating that it is not an object

I am encountering an issue: Error: The object '$rootScope.user.userMessage' is not defined. (evaluating 'typeof $rootScope.user.userMessage') This error arises from the following code snippet: if (typeof($rootScope.user.userMessage ...