Determine the minimum value of an object's keys by comparing them to a given number

Consider the following scenario:

const list = {
  1: "a",
  10: "b",
  20: "c",
  30: "d",
  40: "e"
};

const value = 15;

I am looking for an efficient way to compare the 'value' against the keys in the object and retrieve the corresponding value from the smaller range. In this case, the expected result would be b as 15 falls between 10 and 20.

This was my initial approach:

for(var i=0; i < keys.length; i++){
    const item = parseInt(keys[i],10);
    if (item == keys[i]) {
      return keys[i];
    }
  }

However, I realized that this method is not very efficient...

Answer №1

To retrieve all the keys of an object and stop the loop when a certain condition is met, you can utilize Object.keys to extract the keys into a new array. Then, within the .some method (as recommended by @Keith), you can stop the loop by returning true once the current value exceeds a specified threshold set by the variable value. The final result will be stored in the variable named previous.

const list = {
  1: "a",
  10: "b",
  20: "c",
  30: "d",
  40: "e"
};

const value = 15;
let previous = 0;

Object.keys(list).some(k => {
  if (k > value) {
    return true;
  } 
  previous = k
});

console.log(list[previous]);

Answer №2

If you're looking to find the first index in an array that is greater than a specific value, you can utilize the Array.findIndex() method. If no such index is found (resulting in a return value of -1), then the element at the last key will be selected. Otherwise, the value located at the key preceding the identified index will be chosen. In cases where the value is less than the very first key, the function will return undefined.

const findLowerClosest = (value, arr) => {
  const keys = Object.keys(list);
  const index = keys.findIndex(key => +key > value);
  const atKey = index !== -1 ? index - 1 : keys.length - 1;
  return arr[keys[atKey]];
}

const list = { 1: "a", 10: "b", 20: "c", 30: "d", 40: "e" };

console.log(findLowerClosest(15, list)); // b
console.log(findLowerClosest(75, list)); // e
console.log(findLowerClosest(-3, list)); // undefined

Answer №3

When presented with pre-sorted keys, it is efficient to utilize a binary search algorithm with a time complexity of log(n). By arranging the keys into an array and performing a one-time linear step (with a possible one-time sort operation if needed), this method proves valuable when multiple searches on a single structure are anticipated.

const bisect = (a, target, lo=0, hi=a.length-1) => {
  while (lo <= hi) {
    const mid = ~~((hi - lo) / 2 + lo);

    if (a[mid] === target) {
      return a[mid];
    }
    else if (a[mid] < target) {
      lo = mid + 1;
    }
    else {
      hi = mid - 1;
    }
  }
  
  return a[~~((hi-lo)/2+lo)];
};

const list = {
  1: "a",
  10: "b",
  20: "c",
  30: "d",
  40: "e"
};

const keys = Object.keys(list);
console.log(list[bisect(keys, 15)]);
console.log(list[bisect(keys, 16)]);
console.log(list[bisect(keys, -50)]);
console.log(list[bisect(keys, 50)]);

Answer №4

Utilize the filter function to extract values that are below 15, then apply Math.max, and finally use this result as a key to fetch the corresponding value from the object.

const list = {
  1: "a",
  10: "b",
  20: "c",
  30: "d",
  40: "e"
};

const targetValue = 15;

function retrieveValue(n) {
  let keys = Math.max.apply(null, Object.keys(list).filter((item) => {
    return item < n
  }));
  return (list[keys])
}
console.log(retrieveValue(targetValue))

Answer №5

One way to solve this is by first sorting the keys and then using a reduce function to determine the lower key within the target range:

const list = {
  1: "a",
  10: "b",
  20: "c",
  30: "d",
  40: "e"
};

const value = 15;
const result = list[Object.keys(list)
                     .map(a => parseInt(a))
                     .sort((a, b) => a - b)
                     .reduce((acc, curr) => (acc < value && value < curr) ? acc : curr)];
                     
console.log(result);

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

Tips for successfully parsing JSON data during an Ajax call

After making an Ajax call, the response.responseText I receive looks like this: . "[ columns :[ { "id":"name", "header":"User name" }, { "id":"birth", "header":"Date of birth" } ], ...

Tips for obtaining the sources of every image on a webpage and consolidating them in a single section

My goal is to preload all images on a webpage into a single division before the page loads. For example, if there are 5 images on the page (eg1.png, eg2.jpg, eg3.bmp, eg4.jpg, eg5.png), I want them to be contained within a div with the id 'pre'. ...

Organizing data in an array of structs

I am facing an issue with retrieving and storing songs and lyrics from a sqlite database into an array. The array structure is defined as follows: struct KArray { let SongTitle: String let SongLyrics: String let ESongTitle: String func ma ...

Crafting a model for arrays of objects - a guide to perfection

Why am I experiencing errors in the console when trying to set the API return to a variable? How can this issue be resolved? This is my TypeScript code: public myData = new myDataModel(); getData(){ this.myCoolService.getDataAPI() .subscribe(( ...

Engage the PROTRACTOR refresh function

I'm just getting started with automation and Protractor. I successfully automated the login page, but now I'm facing a challenge with accessing a menu that I need in order to navigate to a different page. Within the menu, there is an href="#/dom ...

EINVAL: the argument provided is invalid for reading

I’m currently using node v11.5 and npm 6.4.1 on a flash drive labeled E, running on Windows 7. My goal is to install the latest version of the Netlify CLI. I followed the steps outlined at , and executed the following command: $ npm install netlify-cli ...

Trouble accessing the Ionic SQLite database: Unable to open

I encountered some errors while attempting to connect my ionic app to a database. I am currently running the app on an android device using Google Chrome DevTools to troubleshoot the issue. Check out the createDatabase() function and the specific error th ...

Generating a random number to be input into the angular 2 form group index can be done by following these

One interesting feature of my form is the dynamic input field where users can easily add more fields by simply clicking on a button. These input fields are then linked to the template using ngFor, as shown below: *ngFor="let data of getTasks(myFormdata); ...

Is there a way to retrieve a particular object from the state and access one of its elements?

I have a component called Tweets.js: import React, {Component} from "react"; export default class Tweets extends Component { constructor(props) { super(props); this.state = {tweets: [], users: []}; } componentDi ...

How to retrieve elements from a struct array that has been passed in C programming

I'm facing a perplexing issue with my method levenshtein. It populates a 2D array of structs with information and returns a pointer to that array. However, when I pass this array to another method, I encounter a dreaded Segmentation Fault (core dumped ...

"Performing a MongoDB Node query within the time frame of 1 hour from

I am having trouble retrieving data with my query to find all objects within the last hour based on timestamps: Here is the schema I am using: var visitSchema = mongoose.Schema({ timestamp: { type: Date, default: Date.now }, userID: String, userName ...

Utilizing Jquery Plugins in Node.js with ES6 Imports: A Comprehensive Guide

I recently started using a jQuery calendar plugin, which can be found at this link: . I have been utilizing it with a CDN, but now I am looking to incorporate it as a Node.js module. What would be the most effective method to achieve this? Edit: Just to ...

Connect-busboy: The file being piped to the write stream is either empty or incorrect, depending on its type

My current project involves testing a file upload feature using connect-busboy. Interestingly, I have encountered a peculiar issue when uploading PNG files - although the file gets uploaded, the content seems to be incorrect and unable to open. Upon furthe ...

Issues with AngularJS edit functionality for records not functioning as expected

I have implemented a feature on my page where users can add objects to an array. These objects are then displayed on the page along with links for editing each item in the array. Each added item is assigned a primary key, allowing users to edit it later e ...

Retrieve isolated scope of directive from transcluded content

I am not certain if it is possible, but I am essentially looking for a reverse version of the '&' isolate scope in AngularJS. You can check out this Plunkr to see an example. In essence, I have created a custom directive that provides some r ...

React timer slide show malfunctioning

While I have some experience with React, I'm struggling with a seemingly simple problem that I just can't figure out. My goal is to cycle through an array of images and display the image at the current index. The console logs show the correct in ...

"Integrating Associated Models with Sequelize: A Step-by-Step Guide

I am attempting to retrieve all transactions along with their associated stripePayments, but I keep encountering the error include.model.getTableName is not a function. In my database schema, there is a table for transactions that has a one-to-many relati ...

Create an image on a node's backdrop using a library of graph theory/networking techniques

I have a set of data that I need to visually represent as a graph on a web browser. While creating the graph itself is not an issue, I am looking to dynamically draw unique icons for each node. These icons are specific to the characteristics of each node ...

Master the art of fetching response data from an API and implementing a function to process the data and generate desired outputs using Node.js and JavaScript

Being new to node.js, javascript, and vue, I attempted to create a Currency Converter by fetching data from an API for exchange rates and performing calculations in a function. Despite successfully obtaining the exchange rates from the selected country in ...

Issue with Bing Maps Infobox mouseout event: Problem arises when attempting to change the htmlContent asynchronously

Can anyone provide assistance? I am currently utilizing the latest Bing Maps version (v8), and I have encountered an issue. When creating a custom Infobox and populating its contents using an async request such as setTimeout/ajax, the mouseout event is tr ...