Skip to content
Advertisement

Javascript Subtract between two arrays of objects

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:

JavaScript

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.

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement