Reputation: 43
I am trying to create a stock trader application and i have an empty array for the stocks bought. Each Stock bought adds an object to the array. if that same stock is bought again, I want to check for the stock and then append ONLY THE QUANTITY TO THAT RELEVANT ARRAY . else i want to append just the new object .
I have tried using the for Each loop and some function , but I cant seem to get the current element that has been bought already and update only its quantity. I am able to get the quantity to be added but not that specific object for it to be appended to .
item is the object to be appended to the array. only quantity if object is already in array; Thanks!
stocks = [
{id:0, name:'BMW', price:5 , quantity:0},
{id:1, name:'Google',price:20, quantity:0},
{id:2, name:'IBM', price:34, quantity:0},
{id:3, name:'Apple', price:15,quantity:0}
];
...
...
stockPortfolio =[]
...
//the item is the
'ADD_PORTFOLIO_ITEM'(stockPortfolio , item){
//checking if an itemid exists
// if not create a new one
const arrayP = stockPortfolio
const found = arrayP.some(el => el.name === item.name);
if (found) {
}
else{
Upvotes: 1
Views: 125
Reputation: 1587
This works for me. Let me know if you face any issues. I am changing the original array of stockPortfolio
. If you wish to return a new array use .slice()
at the start of the function 'addStock'
const stocks = [
{id:0, name:'BMW', price:5 , quantity:0},
{id:1, name:'Google',price:20, quantity:0},
{id:2, name:'IBM', price:34, quantity:0},
{id:3, name:'Apple', price:15,quantity:0}
];
let stockPortfolio = [ ];
function addStock(stockPortfolio , item) {
let found = stockPortfolio .some(el => el.name === item.name)
if (!found) {
stockPortfolio.push(item);
} else {
for (var i = 0; i < stockPortfolio.length; i++) {
if (stockPortfolio[i].name === item.name) {
stockPortfolio[i].quantity += item.quantity;
}
};
};
};
Upvotes: 1
Reputation: 487
const found = stockPortfolio.find(el => el.name === item.name);
if (found) {
// found contains the matched item
} else {
// no match found, add to array
}
Upvotes: 2