Fulfill the specified amounts for each row within a collection of items

I have an array of objects containing quantities. Each object includes a key indicating the amount to fill (amountToFill) and another key representing the already filled amount (amountFilled). The goal is to specify a quantity (amount: number = 50;) and automatically set the amountFilled to match the amountToFill, continuously reducing the value of (amount: number = 50) as the array gets filled until the amount: number equals 0.

When the amountFilled is greater than 0, caution must be taken when calculating the subtraction from the total amount.

DEMO

Initial Outcome

amountArray =[{
    option:'text',
    amountToFill: 5,
    amountFilled:0,
  },
  {
    option:'text1',
    amountToFill: 3,
    amountFilled:1,
  },
  ...
];

Desired Outcome

 amountArray1 =[{
    option:'text',
    amountToFill: 5,
    amountFilled:5,
    filled: true
  },
  {
    option:'text1',
    amountToFill: 3,
    amountFilled:3,
    filled: true
  },
  ...
];

Answer №1

const itemsList =[{ name:'apple', quantityRequired: 10, quantityFilled:0, }, { name:'orange', quantityRequired: 20, quantityFilled:15, }, { name:'banana', quantityRequired: 30, quantityFilled:0, }, { option:'pear', quantityRequired: 15, quantityFilled:8, }];
  
 let totalQuantity = 100;
 const resultArray = itemsList.map(item => {
 const remainingQuantity = item.quantityRequired - item.quantityFilled;
 if (totalQuantity - remainingQuantity > 0) {
    totalQuantity -= remainingQuantity;
  return {...item, quantityFilled: item.quantityRequired, isFilled: !!totalQuantity}
 }
 else {
   const newObject = {...item, quantityFilled: item.quantityFilled + totalQuantity, isFilled: !!totalQuantity}
   totalQuantity = 0;
   return newObject;
 }
 });
  
console.log(resultArray);
  
  
  
  
  

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

SignOut operation in Express.js Firebase instantly responds with a status of 200 to the client-side Fetch POST request

I'm currently facing an issue with my POST request setup using the Fetch API in my client-side JavaScript. The request is being sent to my server-side JavaScript code which utilizes Express Js and Firebase Auth. The problem arises when the auth().sign ...

Tips for ensuring the border matches the size of the image

I am in the process of creating a website that includes a filter option. My plan is to have the filters displayed on the left side and the items on the right side. To achieve this layout, I have implemented a scrollable div for the items. However, I notic ...

JavaScript: Modifying the Style of a :lang Selector

Currently, I am working on creating a basic multilingual static website using only HTML5, CSS3, and vanilla JavaScript. The structure of the HTML looks something like this: <html> <head> <title>WEBSITE</title> ...

When an option is selected in one dropdown, a list is dynamically populated in another dropdown. However, the entire column then displays the selected row's options in a table format

https://i.stack.imgur.com/q7tMT.png Upon selecting an option from a dropdown within a table row, I make a call to an API to fetch a list of strings into another dropdown field for that specific row. However, the entire column is being populated with that r ...

Module is absent in JavaScript but present in TypeScript

As I delve into coding a vscode extension by following a tutorial, I encountered an issue with importing in my server.ts file. The directory structure looks like this: ...

Getting the mssql output in Protractor using VSCode

I recently tried running the code below and it seems like the connection is established successfully. However, I'm unable to see any output. Is there a way to view the query result? I am still learning about Protractor, NodeJS, and MSSQL connections. ...

In React, the error message "Joke.map is not a function" indicates that

export default App I am encountering an error in this code which says joke.map is not a function. Can someone please assist me in finding a solution? I have verified the api endpoints and also checked the function. import { useEffect, useState } from &ap ...

Unable to reach controller action with Ajax request

I've been encountering issues trying to make a Get request to hit the specified URL. Initially, I attempted inputting the URL parameter manually in a separate JS file, then transitioning all my JS to cshtml to test out Razor. However, I am still facin ...

Selenium throws an error message stating 'NoSuchAlertError: no alert is currently opened'

When using Selenium, I encounter an issue where clicking a button triggers an alert box, but accepting the alert box results in an error message. element.click(); driver.switchTo().alert().accept(); The problem is quite unpredictable. ...

Creating a structured state declaration in NGXS for optimal organization

Currently, I'm delving into the world of NGXS alongside the Emitters plugin within Angular, and I find myself struggling to grasp how to organize my state files effectively. So far, I've managed to define a basic .state file in the following man ...

Identifying Master Page Controls Post-Rendering

Within my asp.net projects, I have noticed a discrepancy in the control id on the master page's Contentplaceholder1. On my local server, the id appears as "ctl00_Contentplaceholder1_control" after rendering. However, when the application is deployed t ...

Prevent Scrolling of Body Content within a Specified Div

In my current situation, I am dealing with a large number of divs (over 300) that are being used as part of an interactive background. The issue arises when viewing the page on mobile versus desktop – there are too many divs on desktop, causing excessive ...

Utilize the power of JavaScript to recursively map object keys

I am working with an array of objects that have varying depths. My goal is to output the names in a specific format: Top Level Top Level > Sub 1 Top Level > Sub 1 > Sub 1-2 Top Level > Sub 2 Unfortunately, I am only able to get the name of th ...

Getting Bootstrap columns to work well with Angular ng-show

I am working with three columns in Bootstrap, all set to col-md-4 width. The middle column has an ng-show attribute that may hide it at times. When the rightmost column becomes visible due to friend requests, it displaces the middle column if it's hid ...

Typescript's intriguing concept of objects containing arrays inside other objects

I have a structure similar to this and I am trying to create definitions for types/interfaces, but I am facing issues in making it work correctly. layoutsSet: { 1: { "lg": [ { i: "1", x: 0, ...

Adjust date by one day using the Datetimepicker tool

I have been attempting to adjust the date of my input by one day either forward or backwards, but I seem to be stuck and not making any progress. Take a look at my code: function function backDay() { var date = $('input#datetimepicker').va ...

Getting an error message like "npm ERR! code ENOTFOUND" when trying to install Angular CLI using the command "

Currently, I am eager to learn Angular and have already installed Node version 18.13.0. However, when attempting to install Angular CLI using the command npm install -g @angular/cli, I encountered an issue: npm ERR! code ENOTFOUND' 'npm ERR! sys ...

TypeScript: displaying parameters

variable_field = [["S",".","."],[".","#","."],[".",".","T"]]; <ng-template ngFor let-array [ngForOf]="field_array" let-x="index"> <ng-t ...

Utilizing an Office App Ajax that includes an authentication header, the application connects to a secure Web API 2 backend with CORS

I am currently in the process of developing a content panel application for Office. As part of this project, I need to authenticate an account against a server. To accomplish this, I have implemented my own AuthorizationFilterAttribute on my web api 2 con ...

The `mouseenter` event handler fails to trigger properly on its initial invocation

As I work on a function to remove a CSS class display:hidden; when the mouse enters a specific part of the DOM to reveal a menu, I encounter an issue. Upon loading the page and hovering over the designated area for the first time, the event fails to trigge ...