I'm building a shop system, so when a customer orders some items and tries to save them to the database, I want to subtract the preview product qty from the new qty ordered.
My API is sending that cart items
const cartItems = [
{
_id: 1,
name: 'item one',
price: 12.99,
qty: 6,
},
{
_id: 3,
name: 'item three',
price: 9.99,
qty: 10,
},
{
_id: 2,
name: 'item two',
price: 6.99,
qty: 2,
},
]
And my MongoDB return this value, so how do I substract stock number from qty?
const products = await Product.find({})
[
{
_id: 1,
name: 'item one',
price: 12.99,
stock: 14,
},
{
_id: 2,
name: 'item two',
price: 6.99,
stock: 78,
},
{
_id: 3,
name: 'item three',
price: 9.99,
stock: 54,
},
]
I want to get a result like this:
[
{
_id: 1,
name: 'item one',
price: 12.99,
stock: 8,
},
{
_id: 2,
name: 'item two',
price: 6.99,
stock: 76,
},
{
_id: 3,
name: 'item three',
price: 9.99,
stock: 44,
},
]
CodePudding user response:
Seems a naive double nested loop could be sufficient for iterating both arrays and computing a new products array.
const newProducts = products.map((product) => ({
...product,
stock:
product.stock -
(cartItems.find((item) => item._id === product._id)?.qty || 0)
}));
A more optimal method would be to precompute a map of quantities by id for O(1)
lookups for an overall O(n)
runtime complexity (as opposed to the O(n^2)
of the double-nested loop above).
const quantityMap = cartItems.reduce(
(quantities, { _id, qty }) => ({
...quantities,
[_id]: qty || 0
}),
{}
);
const newProducts = products.map((product) => ({
...product,
stock: product.stock - (quantityMap[product._id] || 0)
}));