Utilizing Javascript to extract an element with a property exceeding a specified amount, yet falling short of the following object in line

I am facing a challenge in my JavaScript code. I have an integer that represents the quantity of an order, and there is an object containing all the quantities offered with their respective prices:

    {
        "1": {
            "quantity": 1,
            "price": 10
        },
        "2": {
            "quantity": 2,
            "price": 20
        },
        "6": {
            "quantity": 6,
            "price": 50
        },
        "12": {
            "quantity": 12,
            "price": 80
        }
    }

The task at hand is to identify the object with a quantity value greater than the order quantity, but smaller than the quantity value of the next object in the sequence.

For instance, if the order quantity is 8, it should pick:

        "6": {
            "quantity": 6,
            "price": 50
        },

This information is crucial for determining the correct price. Even though I have experimented with multiple LoDash methods, none seem to provide the desired outcome. Is there a solution or approach that can help me achieve this?

Answer №1

To determine the count of smaller or equal values, you can reverse the array after obtaining the keys.

function findValues(obj, num) {
    return Object.keys(obj).reverse().find(val => val <= num);
}

var obj = { 1: { quantity: 1, price: 10 }, 2: { quantity: 2, price: 20 }, 6: { quantity: 6, price: 50 }, 12: { quantity: 12, price: 80 } };

console.log(findValues(obj, 8));

Answer №2

After analyzing your description, it seems like you are attempting to locate the record that corresponds to the lowest quantity higher than the input quantity. However, the example provided does not align with that explanation. If you actually intend to find the next largest quantity smaller than the input, you may need to reverse the two inequalities.

    some_prices =  {
        "1": {
            "quantity": 1,
            "price": 10
        },
        "2": {
            "quantity": 2,
            "price": 20
        },
        "6": {
            "quantity": 6,
            "price": 50
        },
        "12": {
            "quantity": 12,
            "price": 80
        }
    }

    getNextQuantityPrice = (prices, quantity) => {
        const largerQuantities = Object.values(prices)
            .filter(value => value.quantity > quantity);
        if (largerQuantities.length === 0) return null;
        return largerQuantities
            .reduce((min, next) => next.quantity < min.quantity ? next : min)
    }

    console.log(JSON.stringify(getNextQuantityPrice(some_prices, 2)));

Answer №3

If you're looking to loop through the keys of a Javascript object, there are plenty of resources available that have addressed this issue repeatedly.

var prices = {
        "1": {
            "quantity": 1,
            "price": 10
        },
        "2": {
            "quantity": 2,
            "price": 20
        },
        "6": {
            "quantity": 6,
            "price": 50
        },
        "12": {
            "quantity": 12,
            "price": 80
        }
    };

for (qty in prices) {
  // Do stuff
  console.log(qty);
}

If you simply want to extract the available quantities (object keys), you can utilize Object.keys(prices), which provides an array for easy iteration.

Once you've converted the data into an array, you can further manipulate it using additional for loops, or explore more advanced options like forEach(), filter(), and similar methods.

Answer №4

In my view, the most effective way to address the fundamental question is to reverse the list, like many other responses have suggested. Instead of relying on the original object's order to be as desired, it is preferable to sort it at the beginning and then carry out the operations in reverse order.

const determineNextQuantity = (quantities) => {
  const reversed = Object .values (quantities) .sort (({quantity: q1}, {quantity: q2}) => q2 - q1)
  return (requested) => reversed .find (({quantity}) => quantity < requested)
}

const quantities = {1: {quantity: 1, price: 10}, 2: {quantity: 2, price: 20}, 6: {quantity: 6, price: 50}, 12: {quantity: 12, price: 80}}

console .log (
  determineNextQuantity (quantities) (8)
)

This approach also allows for storing an intermediate function that eliminates the need to repeatedly reverse the list with every call. The

determineNextQuantity(quantities)
function generates a reusable function for determining the next quantity based on requests.

If maintaining the output format specified in the question is crucial (i.e., not just {quantity: 6, price: 50}, but wrapping the result in a single-property object like {'6': {quantity: 6, price: 50}}), you could reconfigure it as follows:

const determineNextQuantity = (quantities) => {
  const reversed = Object .values (quantities) .sort (({quantity: q1}, {quantity: q2}) => q2 - q1)
  return (requested) => {
    const q = reversed .find (({quantity}) => quantity < requested)
    return {[q.quantity]: q}
  }
}

However, personally I find working with this format to be more challenging.

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

Can a data filter be customized to fit a specific grid layout, ensuring that all images are displayed in a full column or at a designated size?

Check out this awesome box grid https://i.sstatic.net/qbmQz.jpg But here's the issue: when I add a data filter and switch between filters, the images always appear in the same location and size as the original grid. Is there any way to make the filte ...

Guide to transferring a JavaScript/Ajax variable to a PHP webpage with the help of AJAX

function initiateIperfSpeedRequest(speedVar, actualIp) { var xmlhttp = getAjaxObject(); xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { handleIperfResponse(xmlhttp.respo ...

Struggling with replicating the btn-dark style in this multi-level Bootstrap 4 dropdown clone

I'm having trouble getting this multi-level Bootstrap 4 clone dropdown menu to match the appearance of a Bootstrap 4 btn-dark. The colors and styling are all off, and I'm not sure which elements to adjust to achieve the desired look. Any guidance ...

Tips for displaying a recommendation list when entering a tag in Bootstrap Vue

I am currently working on a project using Vue and for styling, I have incorporated BootstapVue. My goal is to create a feature where as a user types in an input field, a filtered array containing relevant values is displayed in a dropdown. The user should ...

The functionality of GET_POST is not functioning properly

I've encountered an issue with my PHP webpage and JavaScript function: function send_answer(){ $.ajax({ type: 'POST', url: '../path2file/file_mine.php', data: {dbf1:1, us:1, re:1}, success: relo ...

Ways to retrieve multiple outcomes in mongoose and merge them into a unified response

When making an API call in Node.js using Mongoose, I want to execute 3 different queries and then combine the results to create a JSON response. Query student .countDocuments({}) .then(studentNumber => { return studentNumber; }) teacher . ...

Every time I attempt to build a React application, I encounter the same error message. I even checked the log file, but it keeps showing the proxy error

An error occurred in the command prompt while installing packages. This process may take a few minutes. Installing react, react-dom, and react-scripts with cra-template... Error: ERR_SOCKET_TIMEOUT The network encountered a socket timeout while trying to ...

Troubleshooting Block-scoped errors on Heroku using Node.js and Express

Currently, I am working with node.js and express on the Heroku platform. While working on the route file, I encountered an issue when using the let keyword. The error message displayed was: SyntaxError: Block-scoped declarations (let, const, function, cla ...

Most secure methods to safeguard videos from unauthorized downloading

How can I increase the security measures to prevent users from easily downloading videos from my website? While I understand that it is impossible to completely stop downloads, I am looking for ways to make it more challenging than just a simple right-cl ...

Struggling to update state in React despite attempts to modify the state

Even though I have set the defaultAccount state to the metamask account, when trying to print it in the code below, it still shows null. The issue arises with fetching the value of defaultAccount. (Please see the error image below) class App extends Compo ...

Python's String Manipulation Techniques

I have unique strings such as - Trang chủ and Đồ Dùng Nhà Bếp which contain special characters. I recently noticed that when these strings are printed, they appear just fine. However, when I convert them to JSON format, the output changes to Trang ...

Changing the format of MediaWiki's information into basic text

When using the MediaWiki API, I found that by clicking this link, it provided me with output for the search term Tiger like this: https://simple.wikipedia.org/w/api.php?action=query&prop=extracts&titles=Tiger&format=json&exintro=1 Here is ...

Pairing a removal request with a JSON entity

I am currently working on a project where I need to delete a specific JSON object from a JSON file once its values are displayed in a form using the AJAX Delete function. In order to achieve this, I have set up a route in Express for the JSON file as shown ...

Discovering the specific URL of a PHP file while transmitting an Ajax post request in a Wordpress environment

I'm currently working on a WordPress plugin and running into some issues with the ajax functionality. The main function of my plugin is to display a form, validate user input, and then save that data in a database. Here is the snippet of code for my ...

Struggling to retrieve JSON information from the database using AJAX

I am facing a challenge when it comes to fetching data from my database using these technologies. Here is the current scenario: var username = $('#username').val(); var password = $('#password').val(); // This IP is just an example fo ...

What could be causing an issue with CORS in ExpressJS in one scenario but not in another?

I am currently in the process of setting up a database and connecting it to various routes. Interestingly, I have been successful with one route ('register') but encountering issues with another ('login'). Whenever I attempt to run the ...

The error message "node Unable to iterate over property 'forEach' because it is undefined" appeared

I am facing an error and unable to find the solution. I believe my code is correct. It is related to a video lesson where I attempt to display popular photos from Instagram using the Instagram API. However, when I try to execute it, I encounter this issue. ...

Webpack behaving strangely with inability to use 'import', while 'require' is functioning properly

I am facing a peculiar issue with webpack. Here is my configuration in webpack.config.js: import webpack from "webpack"; import path from "path"; //not working: import ExtractTextPlugin from "extract-text-webpack-plugin"; const ExtractTextPlugin = requi ...

"Looking to transfer an array of object properties in a Vue.js application? Let's explore

component: To-Do List: <template> <ol> <li v-for="toDo in toDos" :key="toDo.id">{{ toDo.text }}</li> </ol> </template> <script> export default { name: "ToDoList", props: { toDos: Array }, ...

JavaScript - exploring techniques to alter the relationship between parents and children

I'm facing an issue with transforming the parent-child relationship in my data structure. Currently, it looks like this: { "id": 7, "name": "Folder 1", "parent_folder": null, "folders": ...