I have two arrays of objects.
I’m trying to create a function that can subtract values from one array of objects from another array of object using the same id on name in REACT
export default function App() {
const stockArray = [
{ id: 1, name: "Iphone", amount: 23 },
{ id: 2, name: "Samsung", amount: 28 },
{ id: 3, name: "Huawei", amount: 14 },
{ id: 4, name: "Motorola", amount:20 }
];
const basketArray = [
{ id: 1, name: "Iphone", amount: 3 },
{ id: 3, name: "Huawei", amount: 4 }
];
const [stock, setStock] = React.useState(stockArray);
const [basket, setBasket] = React.useState(basketArray);
const handleUpdateStock = () => {
// How to subtract amount values in basketArray from amount values in stockArray
in objects with the same id or name.
// the result should be :
// const stockArray = [
// { id: 1, name: "Iphone", amount: 20 },
// { id: 2, name: "Samsung", amount: 28 },
// { id: 3, name: "Huawei", amount: 10 },
// { id: 4, name: "Motorola", amount:20 }
// ];
}
return (
<div>
<h3>Stock:</h3>
{stock.map(product=> (
<h5>{product.name} - {product.amount} </h5>
))}
<br/>
<h3>Basket:</h3>
{basket.map(product=> (
<h5>{product.name} - {product.amount} </h5>
))}
<button onClick={handleUpdateStock}>Save and update stock </button>
</div>
);
}`
2
Answers
this function iterates all indexes in stockArray, will find same object with the same id in basketArray and if basket is an object, it changes value of amount in stock
You can loop your stock array, and compare each product with in it with each product from the basket.
If they have the same id you should subtract the amount from the
product.amount
from the the product inside the basket.In the end we should setStock with the new array.