1

Example array -

    const arr = [
      {
        charge: [ { id: '1', qty: 10 }, { id: '2', qty: 20 } ],
        totalCharge: 100,
        qtySum: 50
      },
      {
        charge: [ { id: '3', qty: 30 }, { id: '4', qty: 40 } ],
        totalCharge: 70,
        qtySum: 100
      },
    ]

The math actions - (qty * totalCharge) / qtySum

Output (not real numbers) -

    [
      {
        id: '1',
        calcQty: 300,
      },
      {
        id: '2',
        calcQty: 250,
      },
      {
        id: '3',
        calcQty: 300
      },  
      {
        id: '4',
        calcQty: 400
      }
    ]

What I could not understand how to do is to separate the charge and only then do the math I need. Because I need to use the same totalCharge and qtySum each time based on how many organs are in the charge field, would love to get some help

2
  • Use nested loops. Commented Jan 13, 2022 at 17:30
  • The outer loop gets totalCharge and qtySum, the inner loop gets qty. Commented Jan 13, 2022 at 17:31

3 Answers 3

2

You can use a combination of map and flat.

const arr = [
  {
    charge: [
      { id: "1", qty: 10 },
      { id: "2", qty: 20 },
    ],
    totalCharge: 100,
    qtySum: 50,
  },
  {
    charge: [
      { id: "3", qty: 30 },
      { id: "4", qty: 40 },
    ],
    totalCharge: 70,
    qtySum: 100,
  },
];

const res = arr
  .map(({ charge, totalCharge, qtySum }) =>
    charge.map(({ id, qty, stySum }) => ({
      id,
      calcQty: (totalCharge * qty) / qtySum,
    }))
  )
  .flat();

console.log(res);

Sign up to request clarification or add additional context in comments.

Comments

1

You can use forEach twice to get the math action done.

Try like below.

const arr = [
  {
    charge: [
      { id: "1", qty: 10 },
      { id: "2", qty: 20 },
    ],
    totalCharge: 100,
    qtySum: 50,
  },
  {
    charge: [
      { id: "3", qty: 30 },
      { id: "4", qty: 40 },
    ],
    totalCharge: 70,
    qtySum: 100,
  },
];

const output = [];

arr.forEach(({ charge, totalCharge, qtySum }) => {
  charge.forEach(({ id, qty }) => {
    output.push({ id, calcQty: (qty * totalCharge) / qtySum });
  });
});

console.log(output);

Comments

1

You could map nested arrays and get a flat result.

const
    array = [{ charge: [{ id: '1', qty: 10 }, { id: '2', qty: 20 }], totalCharge: 100, qtySum: 50 }, { charge: [{ id: '3', qty: 30 }, { id: '4', qty: 40 }], totalCharge: 70, qtySum: 100 }],
    result = array.flatMap(({ charge, totalCharge, qtySum }) =>
        charge.map(({ id, qty }) => ({
            id,
            calcQty: qty * totalCharge / qtySum
        }))
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.