Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

234
Vistas
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:

 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 :)

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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}`,
    };
  }
});
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda