-1

I'm new to javascript, and I want to deduct Quantity in openOrders from Stock in cybertill, where SKU matches to Ref

cybertill = [
{
    Ref: 'BLD188',
    Stock: '4',
  },
  {
    Ref: 'BEX1403',
    Stock: '7',
  }
];

openOrders = [
{
    SKU: 'BLD188',
    Quantity: '1',
  },
  {
    SKU: 'BEX1403',
    Quantity: '2',
  }
];

Im trying to get one object array that has the difference between the Stock and the Quantity, t

stockLeft = [
{
    Ref: 'BLD188',
    Stock: '3', //Which is 4 - 1
  },
  {
    Ref: 'BEX1403',
    Stock: '5', //Which is 7 -2
  }
];

1 Answers1

0

You may map over the cybertill array, where map will construct a new array based on the logic you need.

The logic you have is to calculate the difference, based on the Ref and the SKU attributes, between the Stock values you have in the cybertill array and the Quantity values found in the openOrders array.

To do so, we may pass a function to the map method, that iterates over the cybertill array, that, at each iteration, constructs an object that will have the Ref and the difference we calculated (saved in the Stock attribute of that new object).

So to illustrate, here's a live demo describing the above logic:

const cybertill = [{
      Ref: 'BLD188',
      Stock: '4',
    },
    {
      Ref: 'BEX1403',
      Stock: '7',
    }
  ],
  openOrders = [{
      SKU: 'BLD188',
      Quantity: '1',
    },
    {
      SKU: 'BEX1403',
      Quantity: '2',
    }
  ],
  /** map (loop) over "cybertill" and construct an array containing the desired diff values */
  stockLeft = cybertill.map(o => {
    /** 
     * o: holds an object from "cybertill" at each iteration.
     * d: the object that will hold the difference of the current iteration.
     * order: holds the object that has the same "Ref" in the "open,Orders" array.
     */
    const d = o,
      order = openOrders.find(oo => oo.SKU == o.Ref);

    /**
     * if we have found an entry in "openOrders" that matches the current "Ref" (o.Ref) then we do the substraction.
     * otherwise the diff object will be the same as the "o" (the current iteration's object from "cybertill" array).
     */
    order && (d['Stock'] -= order.Quantity);

    /** retrun the constructed order that will likely to have the diff we want */
    return d;
  });

/** print the result */
console.log(stockLeft);

In the above demo, the array stockLeft should be equal to:

[
  {
    "Ref": "BLD188",
    "Stock": 3
  },
  {
    "Ref": "BEX1403",
    "Stock": 5
  }
]
ThS
  • 4,597
  • 2
  • 15
  • 27