Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to implement a map method into another map method?

I have an object that I map within a React component to render some stuff. Each item in the array has another array payroll_run_items inside. I would like to get the sum of amount of all items in that sub-array within my map method. Is this even possible within map (s.th. like creating a map inside a map)? I could only make it happen via looping and calculating the value beforehand outside the map method.

payrollRuns object:

(23) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0:
amount: "0.00"
company: {id: 1, name: 'Example Ltd.', country: 'Germany', city: 'Munich', zip: '80801', …}
line_items: 0
month: {id: 55, period: '2024-03-01'}
payroll_run_items: Array(4)
0: {id: 338, amount: '3780.00', offer: {…}, month: {…}, payroll_run: {…}}
1: {id: 361, amount: '4428.28', offer: {…}, month: {…}, payroll_run: {…}}
2: {id: 384, amount: '3780.00', offer: {…}, month: {…}, payroll_run: {…}}
3: {id: 407, amount: '3780.00', offer: {…}, month: {…}, payroll_run: {…}}
const PayrollRuns = (props) => {

    const runItems = props.payrollRuns.map((run) =>
        <div key={run.id} className="flex p-4 text-lg">
          ..
          <div>{sum of all amounts of payroll_run_items array..}</div>
        </div>
    );

    return (
        <div className="runs-wrapper bg-white rounded-xl h-full w-48 shadow-sx-shadow p-4 flex flex-col">
            <h1 className="border-b-2 pb-4">Payroll Runs</h1>
            <div className="grow overflow-auto">{runItems}</div>
        </div>
    )
}

export default PayrollRuns

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes, you need to use reduce:


const runItems = props.payrollRuns.map((run) =>
        <div key={run.id} className="flex p-4 text-lg">
          ..
          <div>{run.payroll_run_items.reduce((acc, value) => {
  return acc.amount + value.amount;
})}</div>
        </div>
    );

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading