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

220
Vistas
Calculate previous element as input to next element of array in JS?

I have following code to calculate Stock value dynamic based on the previous calculated value

and also the only last value of element we have currentStock field which will be useful to calculate dynamic stock

this.stockList.map(function(product, index) {
 product.Data.map(function(attribute, currentIndex) {
   if (currentIndex == 0) {
     attribute.stock = attribute.currentStock;
   } else {
     const requestVal = (attribute.qty * attribute.unit) + attribute.stock;   // here i need to have a previous stock value 
     console.log("requestVal", attribute);
     attribute.stock = requestVal;
   }
 });
}); 

my sample expected array :

[
  {
    Product: ABC
    Data: [
      { "billDate": "1-apr-2016", "unit": 2, "Qty": 4, "Amount": 4500, "currentStock": 10 },
      { "billDate": "1-may-2016", "unit": 3, "Qty": 2, "Amount": 4500, "stock": (2 * 3) + 10 = 16 },
      { "billDate": "1-may-2016", "unit": 1, "Qty": 2, "Amount": 4500, "stock": (2 * 1) + 16 = 18 },
    ],
  },
]
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Observation/Suggestion :

  • It should be attribute.Qty instead of attribute.qty
  • In second iteration, You can use product.Data[currentIndex - 1].stock to get the previous object stock value.

Try this :

const stockList = [
  {
    Product: 'ABC',
    Data: [
      { "billDate": "1-apr-2016", "unit": 2, "Qty": 4, "Amount": 4500, "currentStock": 10 },
      { "billDate": "1-may-2016", "unit": 3, "Qty": 2, "Amount": 4500 },
      { "billDate": "1-may-2016", "unit": 1, "Qty": 2, "Amount": 4500 },
    ],
  },
];

stockList.forEach(function(product, index) {
 product.Data.forEach(function(attribute, currentIndex) {
   if (currentIndex === 0) {
     attribute.stock = attribute.currentStock;
   } else {
     const requestVal = (attribute.Qty * attribute.unit) + product.Data[currentIndex - 1].stock;
     attribute.stock = requestVal;
   }
 });
});

console.log(stockList)

about 4 years ago · Santiago Trujillo 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