Question:
Message: This is a function I’m going to implement in my very first project (Which is a point-of-sale system) using Vue Js and I wrote this function using pure JavaScript to simplify this question. So I’d be really grateful if somebody could help me with this problem so I can continue building my practice project. Thanks ❤️My code explanation: I have an empty array called newArray.And an array called mainArray with some records. And I’ve included a button with an onClick event that triggers the function clicked() with an argument passed to it, which is 2 in this case.
What I’m expecting to get: I want to check for a record inside the newArray which contains an id with 2. If such a record is found, I want to add the stock value by 1 in the record. If such a record is not found inside the newArray loop through the mainArray and copy the record which has the id of 2 and add it to the newArray and reset the stock to 1 (So when we click the button again, the record which has id 2 is already there inside the newArray, therefore, I want to add 1 to it, So the stock: 2 now). I have attempted on this problem, and I have attached the code.
Summary according to my project: I have looped through mainArray in my project, so each record has a button with clicked() function, with an attribute called productId, productId is passed as the argument to the clicked() function, I’m expecting: If I click on a button it takes productId as the argument and the function loops through the newArray finding for a record which has id equal to the productId If such record is there add stock by 1. If such record is not there grab the record from the mainArray which has the id equal to the productId value and put inside the newArray by setting the stock value to 1 (stock: 1). So when I click the same button which has the same attribute value it will add 1 to the stock in the record of the same value equal to the id inside the newArray (therefore the stock: 2 now) If again click stock will be stock: 3 so on adding by 1.
Answer:
Suggestion : movenewArray
outside the clicked function as it is going to update on click.Implementation : You can use Array.filter() method on
newArray
to check if record as per the input id is available or not and then by using Array.find() you can do filtering on the mainArray
if there is no data in newArray
.Live demo :
If you have better answer, please add a comment about this, thank you!