Navigating through functions and saving outcomes

I need help creating a function that groups JSON elements based on a specific criteria, but I am having trouble with my loop. The goal is to create groups of 12 bottles and return a single JSON list. For example, in this case, the function should extract the first 3 items and then continue extracting the remaining ones until a group of 12 is completed. However, my loop seems to be running endlessly. Thank you for any assistance.


var data = {
    "order": [
        { "product": "MAXIMUS", "quantity": "3" },
        { "product": "COLECCION", "quantity": "3" },
        { "product": "CABERNET FRANC", "quantity": "6" },
        { "product": "CHARDONNAY", "quantity": "6" },
        { "product": "SAUVIGNON BLANC", "quantity": "6" }
    ]
};

var qtd = data.order;
var size = qtd.length;
var addline = '';
var add = '';
var total = 0;
var i = 0;
var a = 0;
var c = '';

function MakeList(i, add) {
    for (i < 0; total < 12; i++) {
        total += parseInt(qtd[i].quantity);
        addline = addline + '{' + '"quantity": "' + qtd[i].quantity + ' units"},';
        i = i++;
        add = '{"Box of 12":[' + addline.slice(0, -1) + "]}";
    }
    return [i, add];
}

function BuildLabels(i, add) {
    for (i < 0; c = "true"; i++) {
        c = a[0] < size;
        a += MakeList(i, add);
        i = i++;
    }
    return a;
}

var results = BuildLabels(i, add);
output = { id: 3, results };

Answer №1

for (i < 0; c = "true"; i++)

It seems like there is a mistake in the loop condition here. You are assigning the value "true" to c instead of comparing it with double equals ==. Also, the initialization of i should be set to 0. This may cause the variable results to be equal to 0 in the end. Consider revisiting this code to achieve the desired functionality:

var data = {
    "order": [
        { "product": "MAXIMUS", "quantity": "3" },
        { "product": "COLECCION", "quantity": "3" },
        { "product": "CABERNET FRANC", "quantity": "6" },
        { "product": "CHARDONNAY", "quantity": "6" },
        { "product": "SAUVIGNON BLANC", "quantity": "6" }
    ]
};

function MakeList(data) {
    var selected = [], bottlesNum = 0;
    for (var i = 0; bottlesNum < 12; i++) {
        selected.push(data.order[i]);
        bottlesNum += parseInt(data.order[i].quantity);
    }
    return selected;
}

    var results = MakeList(data);
    // now it is a JS object:
    console.log({ id: 3, results: results });
    // if you want it to be a JSON string, use JSON.stringify():
    console.log(JSON.stringify({ id: 3, results: results }));
  

Give it a try and see if it works as expected.

UPDATE

var data = {
    "order": [
        { "product": "MAXIMUS", "quantity": "3" },
        { "product": "COLECCION", "quantity": "3" },
        { "product": "CABERNET FRANC", "quantity": "6" },
        { "product": "CHARDONNAY", "quantity": "6" },
        { "product": "SAUVIGNON BLANC", "quantity": "6" }
    ]
};

function makeGroup(data, max) {
    var selected = [], bottlesNum = 0;
    while(data.order.length) {
      if(bottlesNum + +data.order[0].quantity > max) break;
        var order = data.order.shift();
        bottlesNum += +order.quantity;  // casting to Number
        selected.push(order);
    }
    return selected;
}

function splitOrder(data, max) {
 while(data.order.length) {
    var results = makeGroup(data, max);
    if(!results.length) {
      console.log("Error: a product's quantity is greater than max. size of the group. Try to increase max. size of the group."); 
      break;
    }
    console.log({ results: results });
 }
}
// 2nd argument - max. size of the group. In case of 12 there will be 2 groups - of 3, 3, 6 and 6, 6 bottles
splitOrder(data, 12);

// Also notice that if max. size of the group is a changing value and can be set somehow to, lets say, 4 which is fewer than number of some products (6) in our order. So, it is impossible to complete such a task without taking some additional steps to handle this situation. For example, we could filter our data beforehand to exclude products with numbars greater than 4 and then form groups based on the rest of the data. Or we can treat products with number equal to 6 as if they satisfy our constraint etc.

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

What is the most effective way to retrieve data from a URL and process it using reactjs?

Looking to consume JSON data from a URL, here is an example of the JSON structure: { "results": [ ... ], "info": { ... } } I aim to display the fetched data as a component property. What is the most efficient way to achie ...

What is the best method for converting a modified array back to JSON format?

I'm currently working on a Discord bot that allows users to use the command tcp freeitem to receive a free item. My goal is to update the Account object by adding a new item to the account. However, when I attempt to map the array to replace a value, ...

How to define a TypeScript recursive object with a defined endpoint?

Welcome to my first question! I am currently facing an issue with defining an object to store strings in multiple languages. I am looking for a flexible solution and have considered using a nested object structure. However, I want the final object to adhe ...

What is the best way to initiate a re-render after updating state within useEffect()?

I'm currently strategizing the structure of my code using React hooks in the following manner: Implementing a state variable to indicate whether my app is loading results or not The loading state turns to true when useEffect() executes to retrieve da ...

Is there a way to determine the actual time or percentage completion of a file upload using Telerik RadUpload?

Utilizing the Telerik upload file control with manager is a key component of my project: <telerik:RadUpload ID="RadUpload" Runat="server" MaxFileInputsCount="5" /> <telerik:RadProgressManager ID="RadProgressManager" Runat="server" /> For clie ...

Having difficulty retrieving an item from a knockout observable array

When fetching data from a web API and pushing it into an observable array, I wanted to make the items in the array observable as well. Unfortunately, I found that I couldn't access the object if I made it observable. function UpdateViewModel() { ...

Issue with Pagination functionality when using Material-UI component is causing unexpected behavior

My database retrieves data based on the page number and rows per page criteria: const { data: { customerData: recent = null } = {} } = useQuery< .... //removed to de-clutter >(CD_QUERY, { variables: { input: { page: page, perPag ...

Lack of intellisense support for .ts files in Visual Studio Code

Currently, I am using Visual Studio Code 1.17.2 on Arch Linux to kickstart my work with Node.js/Angular4. To avoid confusion caused by loosely typed code, I have decided to switch to TypeScript for my NodeJS server as well. This is why my main file is name ...

I possess a dataset containing lists of dictionaries, which I will transform using json_normalize before adding it to a fresh dataframe

Below is an example of a row from themesdf: [{'code': '1', 'name': 'Economic management'}, {'code': '6', 'name': 'Social protection and risk management'}] I am attempting to ...

Tips for executing a never-ending blocking operation in NodeJS?

Currently, I have a collection of API endpoints within Express. One specific endpoint triggers a lengthy process that hinders the flow of other incoming requests in Express. I am determined to transform this process into a non-blocking one. In order to ga ...

Incorporate 3 additional compound filters with shuffle.js

Is there a way to add a third compound filter to the existing shuffle.js code provided below? // ES7 will have Array.prototype.includes. function arrayIncludes(array, value) { return array.indexOf(value) !== -1; } // Convert an array-like object to a r ...

The issue arises when attempting to use a JavaScript marker within an array, as it

At the moment, I am in the process of building a website that includes a Google map showcasing my custom markers. Each marker is linked to a specific URL, and the connection is straightforward (as shown with one of my markers below) - var image = 'p ...

Posting values using AJAX in PHP - A guide

test.html <html> <!-- To access the complete PHP-AJAX tutorial, please visit http://www.php-learn-it.com/tutorials/starting_with_php_and_ajax.html If you found this tutorial helpful, a backlink to it would be greatly appreciated. ...

How can these lines be drawn in a simple manner?

I have been using the div tag to create a line, but I'm looking for an easier solution. If you have another method in mind, please share it with me. #line{ background-color:black; height:1px; width:50px; margin-top:50px; margin-left:50px; f ...

Unable to open javascript dialog box

One issue I encountered involves a jqGrid where users have to click a button in order to apply any row edits. This button is supposed to trigger a dialog box, which will then initiate an ajax call based on the selected option. The problem lies in the fact ...

Utilizing a shared service for multiple JSON datasets in AngularJS: A beginner's guide

After successfully creating a service that retrieves data from a local JSON file and uses it in a controller to display it in the browser, everything seems to be working well. Here is the code snippet: JavaScript Code: var myApp = angular.module("myApp", ...

How can I transfer a JavaScript value to PHP for storage in an SQL database?

<script> var latitudeVal = document.getElementById("latitude"); var longitudeVal = document.getElementById("longitude"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); ...

When JSON does not substitute variables

I'm currently working with Twig PatternLab. Encountered a minor issue involving JSON and a Twig for loop. Within Atom 00-h3-black.twig: <h3 class="A-ChevronBlack"><a href="">{{ text.chevron }}</a></h3> For Molecule 00-maste ...

What is the technique for anchoring elements at the top of the page when scrolling?

There is a common design feature where the sidebar on the left starts at a lower position on the page, but as you scroll it moves up to the top and remains fixed in place instead of disappearing off the screen. This is a popular design trend that I have ...

What could be the reason for req.route displaying the previous route instead of

Question: const router = express.Router(); router .route('/:id') .delete( validate(messageValidator.deleteById), MessageController.deleteById, ) .get( validate(messageValidator.getById), MessageController.getById, ); ...