Allocate Shares Following Instruction List

Below is the coding question:

Assuming I bought 165 shares at the following rate:

Number of shares Price per share
23 2.5
47 2.54
45 2.56
50 2.6

Allocate the 165 shares using the following instruction:

  • 50 shares to account1,
  • 53 shares to account2,
  • 17 shares to account3,
  • 45 shares to account4.

All of the account must be allocated based on “Lowest Price First Top to Bottom”

I’ve gotten this far with it:

let shares = [
    { numOfShares: 23, price: 2.5 },
    { numOfShares: 47, price: 2.54 },
    { numOfShares: 45, price: 2.56 },
    { numOfShares: 50, price: 2.6 },
  ];
  let allocate = [
    { numToAllocate: 50, name: "account1" },
    { numToAllocate: 53, name: "account2" },
    { numToAllocate: 17, name: "account3" },
    { numToAllocate: 45, name: "account4" },
  ];

  for (let eachAllocate of allocate) {
    let num = eachAllocate.numToAllocate;
    let numOfShares = 0;
    for (let eachShare of shares) {
      num -= eachShare.numOfShares;
      if (num > 0)
        console.log(
          `Account: ${eachAllocate.name}, Quantity Assigned: ${eachShare.numOfShares}, trade price: ${eachShare.price}`
        );
      if (num <= 0) {
        console.log(
          `Account: ${eachAllocate.name}, Quantity Assigned: ${
            num + eachShare.numOfShares
          }, trade price: ${eachShare.price}`
        );
        numOfShares = parseInt(num * -1);
        console.log(numOfShares);
        break;
      }
    }
  }

Output:

Account: account1, Quantity Assigned: 23, trade price: 2.5
Account: account1, Quantity Assigned: 27, trade price: 2.54
20
Account: account2, Quantity Assigned: 23, trade price: 2.5
Account: account2, Quantity Assigned: 30, trade price: 2.54
17
Account: account3, Quantity Assigned: 17, trade price: 2.5
6
Account: account4, Quantity Assigned: 23, trade price: 2.5
Account: account4, Quantity Assigned: 22, trade price: 2.54
25

So here my problem is, I am not quite sure how to enforce it so each time I go through eachAllocate it doesn’t start from beginning, it continues from where it’s left off.. So 20, 17, 6, 25 are numbers where it’s left off from previous allocation…