Hi can anybody help me to implement the right/clean way of subtracting between two arrays of object. My case (backend) is that I fetch Products data from mongodb, then I also have Trolley data that is fetched from MySql, what I’m trying to do is that if product stock is subtracted by quantity in trolley & the result is lower then 0 then I will throw error. Right know my Implementation as below:
const trolleyProducts = await Trolley.findAll({ where: { userId, isActive: true, }, attributes: ["id", "productId", "quantity", "notes"], }); const products = await ProductModel.find( { dbId: trolleyProductIds, }, { _id: 0, sku: 0, barcode: 0, reservedStock: 0, sold: 0, tags: 0, infos: 0, photosURL: 0, } ); // ******* here is my implementation ******* products.map((product) => { trolleyProducts.map((trolley) => { if (product.dbId === trolley.productId) { if (product.stock - trolley.quantity < 0) { throw { name: "Bad Request", message: " Stock is less than desired quantity", }; } } }); }); // **************
Please let me know if there are better & cleaner approach then mine (for performance matter). Thanks 🙂
Advertisement
Answer
You can convert trolleyProducts
to an object whose keys are the product IDs. That way you won’t need a nested loop to find the matching product.
Also, map()
should be used when the callback function returns a value and you’re making an array of those values. Use forEach()
if the loop is for side effect only.
const trolleyProducts = await Trolley.findAll({ where: { userId, isActive: true, }, attributes: ["id", "productId", "quantity", "notes"], }); // convert array to object. trolleyProducts = Object.fromEntries(trolleyProducts.map(obj => [obj.productId, obj])); const products = await ProductModel.find({ dbId: trolleyProductIds, }, { _id: 0, sku: 0, barcode: 0, reservedStock: 0, sold: 0, tags: 0, infos: 0, photosURL: 0, }); products.forEach((product) => { const trolley = trolleyProducts[product.dbId] if (trolley && product.stock - trolley.quantity < 0) { throw { name: "Bad Request", message: `Stock is less than desired quantity for ${product.dbId}`, }; } });