Make sure to not update until all the necessary checks have been completed successfully

My goal is to update an array of objects only after all the necessary checks have passed. I have one array of objects representing all the articles and another array of objects representing the available stock.

I want to make sure that all the articles are in stock before updating the stock array. Here is the code I currently have:

const articles = [{
    "id": "1",
    "quantity": "4"
}, {
    "id": "2",
    "quantity": "8"
}, {
    "id": "4",
    "quantity": "1"
}];

let stock = [
    {
      "id": "1",
      "stock": "6"
    },
    {
      "id": "2",
      "stock": "6"
    },
    {
      "id": "3",
      "stock": "2"
    },
    {
      "id": "4",
      "stock": "2"
    }
  ];

articles.map(article => {
  stock.map(item => {
    if(item.id === article.id){
      if(article.quantity <= item.stock){
        item.stock = item.stock - article.quantity;
      } else {
             console.log('error');
             throw error;
      }
    }
   });
 });

The issue with this solution is that it updates the stock for id = 1 even when the stock for id = 2 is not enough. I want to ensure that all the articles are in stock in sufficient quantity before updating them in the stock array. Ideally, the stock array should be updated as follows:

stock = [
    {
      "id": "1",
      "stock": "2"
    },
    {
      "id": "2",
      "stock": "6"
    },
    {
      "id": "3",
      "stock": "2"
    },
    {
      "id": "4",
      "stock": "2"
    }
  ];

Can anyone provide suggestions on how I can resolve this issue?

Answer №1

One option is to utilize the Array.prototype.find() method. It's important to note that this code snippet assumes that all articles contain an "id" property and does not account for "art_id".

const articles = [{
  "id": "1",
  "quantity": "4"
}, {
  "id": "2",
  "quantity": "8"
}, {
  "id": "4",
  "quantity": "1"
}];

let stock = [{
    "id": "1",
    "stock": "6"
  },
  {
    "id": "2",
    "stock": "6"
  },
  {
    "id": "3",
    "stock": "2"
  },
  {
    "id": "4",
    "stock": "2"
  }
];


// Use Array.prototype.some() to check for items that don't have enough stock
const haveEnough = !articles.some(article =>
  // Convert "1" to 1
  parseInt(
    // Find the stock item with the matching id
    stock.find(stock => stock.id === article.id).stock
  ) <
  parseInt(article.quantity))

console.log(haveEnough)

Afterwards, you can update the stock as shown below:

if (haveEnough) {
 // Perform desired actions
}

Answer №2

I believe that the art_id key within the articles array should actually be named id.

It's not possible to accomplish everything in a single loop, so you'll need to iterate through all the articles first to check if their stock is sufficient, then loop through them again to update the existing stock:

const articles = [
  {
    id: '1',
    quantity: '4',
  },
  {
    id: '2',
    quantity: '5',
  },
  {
    id: '4',
    quantity: '1',
  },
];

let stock = [
  {
    id: '1',
    stock: '6',
  },
  {
    id: '2',
    stock: '6',
  },
  {
    id: '3',
    stock: '2',
  },
  {
    id: '4',
    stock: '2',
  },
];

// Check if any articles have insufficient stock
const outOfStockArticles = articles.find((article) => {
  const articleStock = stock.find((stock) => stock.id === article.id);
  return Number.parseInt(article.quantity) > Number.parseInt(articleStock.stock);
});

// Update stock values if no articles are out of stock
if (!outOfStockArticles) {
  articles.forEach((article) => {
    const articleStock = stock.find((stock) => stock.id === article.id);
    articleStock.stock = Number.parseInt(articleStock.stock) - Number.parseInt(article.quantity);
  });
}

Answer №3

It appears that there is a discrepancy in your articles array. It seems that some articles are labeled with an "art_id" while others have an "id" instead of "art_id".

To resolve this issue, you can utilize the Array.prototype.find function to locate the specific article, and then use the isAvailable function to verify if the article is available in the correct quantity in the stock list.

You can leverage the Array.prototype.every function to achieve the desired outcome. This function will only return true if all elements in the array meet the specified condition, in this case, the isAvailable function.

Check out this simple code snippet:

const articles = [{
  "art_id": "1",
  "quantity": "4"
}, {
  "art_id": "2",
  "quantity": "8"
}, {
  "art_id": "4",
  "quantity": "1"
}];

const stock = [{
    "id": "1",
    "stock": "6"
  },
  {
    "id": "2",
    "stock": "6"
  },
  {
    "id": "3",
    "stock": "2"
  },
  {
    "id": "4",
    "stock": "2"
  }
];

const isAvaiable = (article) => {
  return stock.find(element => element.id === article.art_id).stock >= article.quantity;
}

if (articles.every(isAvaiable)) {
  console.log("I can update")
} else {
  console.log("I cannot update")
}

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

Where to Locate a String Excluding <a> Tags?

I'm in the process of writing a JavaScript code that will scan an HTML document and identify all occurrences of a specific keyword that are NOT contained within a link, meaning not under an <a> tag. To illustrate this, let's examine the fol ...

Experimenting with throws using Jest

One of the functions I'm testing is shown below: export const createContext = async (context: any) => { const authContext = await AuthGQL(context) console.log(authContext) if(authContext.isAuth === false) throw 'UNAUTHORIZED' retu ...

Ensuring Data Accuracy Prior to Saving in Zend Framework 1.12

My form includes validations and a function to save data using ajax. Here is the structure of my form: <form name="enquiry_form" method="post" id="enquiry_form"> Full Name: <input name="name" id="name" type="text" pattern="[A-Za-z ]{1,20}" on ...

Angular mat-select is having difficulty displaying options correctly on mobile devices or devices with narrow widths

In my Angular project, I've encountered an issue with mat-select when viewing options on mobile or low-resolution screens. While the options are still displayed, the text is mysteriously missing. I attempted to set the max width of the mat-option, but ...

Utilizing AngularJS routes to load a specific URL when accessing a page for the first time

Working on developing a Single Page Application using AngularJS, my configuration settings appear as follows: app.config(["$routeProvider", function($routeProvider) { return $routeProvider .when("/", { redirectTo: " ...

Generating instances of classes using variables in Typescript

Are there methods to modify the below piece of code in order for it to be compatible with Typescript? public shops: string[] = [ "AShop", "BShop", "CShop", ]; this.shops.forEach((shop, index) => { let instance = new window[shop](index ...

Having trouble with @here/maps-api-for-javascript in Next.js - it's not functioning

Can anyone help me understand why @here/maps-api-for-javascript is not functioning properly in my Next.js application and producing the following error message: import H from "@here/maps-api-for-javascript"; export default H; ^^^^^^ SyntaxErr ...

php utilizing javascript to generate encrypted data for a hidden file

Within my MVC application, I have implemented Raty for rating images. Below is the code snippet: <div class="container"> <form method="post" class='form' role='form' action="?section=photo&view=addVote"> <input t ...

Is there a way to reverse the confirmation of a sweet alert?

Hey there, I'm currently using Sweet Alert to remove a product from my website. I want to implement it with two options - 'ok' and 'cancel'. However, I'm facing an issue where clicking anywhere on the page removes the product ...

Display laravel view using JavaScript Ajax

I seem to be facing a challenge in displaying the desired view after invoking the controller method via Ajax. Below is the JavaScript function where I trigger the controller Method 'create_pedido' using an Ajax post request. $('.small-box&a ...

A step-by-step guide on extracting nested ASP.NET DataGrid values with JavaScript

Looking to retrieve data from a nested data grid on an aspx page using JavaScript. Check out the following code snippet: <tr> <td colspan="2" align="center"> <asp:DataGrid ID="sampleData" AutoGenerateColumns="false" runat="serv ...

Troubleshooting: Scope not updating in AngularJS xeditable typeahead

Currently, I am utilizing the angular xeditable typehead directive to display an autocomplete dropdown. The data is being retrieved from a JSON file on the page and utilized in the jso array for e-typeahead functionality. When typing into the input field, ...

h1 tag set for jQuery AJAX activation

Currently working on a website that heavily relies on ajax. Encountering an issue that hasn't been solved through online resources. Now, I'm sharing my function for fetching a page: function loadTemplate(name, replaceWholePage = true){ $.wh ...

Understanding array manipulation in a Jade file using Node.js

I have an array in my view route that is set as follows: [ 'dgdgd', 'gdgdfg', 'gdgd', 'dgdg', 'gdfdg', 'gdg'] In the jade file, I have written the following code: select#e1.col-md-12. ...

Is there a universal method to transform the four array values into an array of objects using JavaScript?

Looking to insert data from four array values into an array of objects in JavaScript? // Necessary input columnHeaders=['deviceName','Expected','Actual','Lost'] machine=['machine 1','machine 2&apo ...

What is the best way to retrieve a JSP parameter dynamically or how can one create a JSP parameter on the

Currently learning JSP and ajax simultaneously. In the process of creating a dynamic tab that can be added or removed using these steps. Looking to pass parameters from controller to the content area of the newly added tab. 1. When clicking on the &apos ...

Is it possible to categorize elements for focus and onblur events?

In my search feature, I have implemented an autocomplete div that appears when the user types in a search field. The issue I am facing is that I want the div to disappear when the user clicks outside of it. Here is what I have attempted: //SHOW THE DIV WH ...

What causes the difference in behavior between using setInterval() with a named function as an argument versus using an anonymous function?

I can't seem to figure out why using the function name in setInterval is causing issues, while passing an anonymous function works perfectly fine. In the example that's not working (it's logging NaN to the console and before the first call, ...

Implementing Dynamic Script Injection in Angular Controllers for Enhanced HTML Functionality

I'm a total beginner when it comes to Angular and frontend development, so please bear with me if my question seems basic: In my controller, I have the following code where I am populating the $window.user data that is being used in the script [2] ad ...

Angular: displaying dates in a specific format while disregarding time zones

Is there a way to format date-time in Angular using DatePipe.format() without converting timezones, regardless of location? For instance, for various examples worldwide (ignoring time differences) I would like to obtain 07/06/2022: console.log('2022-0 ...