Search code examples
javascriptarraysobjectcalculated-columns

How to add numbers from items in an array of objects in Javascript to output to a table


This is the array: Data from year:

[{"Years":2023,"New":305,"Updates":360},
 {"Years":2022,"New":334,"Updates":467},
 {"Years":2021,"New":272,"Updates":502},
 {"Years":2020,"New":291,"Updates":377},
 {"Years":2019,"New":327,"Updates":365}]

I have working code to create a table of Year, New, Updates and Total.

<tbody>
{parsedAdmin2ReportData.map((row, index) => (
  <tr key={index}>
    <td>{row.Years}</td>
    <td>{row.New}</td>
    <td>{row.Updates}</td>
    <td>{row.New + row.Updates}</td>
    <td>{parsedAdmin2ReportData[index].New}</td>
  </tr>
))}
</tbody>

I want to add another column that shows the YoY % change but can't get the value of the previous year

For example for 2023 the YoY Change formula would be ((row New of 2022 + row Updates of 2022) -(row New + row Updates))/(row New of 2022 + row Updates of 2022)

The number would show as a percentage Value, red if negative and green if positive.
There would be no calculation for the 2019 row.

I thought I could navigate the index like parsedAdmin2ReportData[index-1].New

but that did not work. I also tried index — and it did not work. Is there a way to get the values in the table and run mathematical functions on them.

Any suggestions?


Solution

  • You can do some additional computations within your map function.

    <tbody>
    {parsedAdmin2ReportData.map((row, index, arr) => ({
      let yoy = "";
      if (index < arr.length - 1) { // it's not the last row
        let nextRow = arr[index + 1]; // get the next row
        let nextTot = nextRow.New + nextRow.Updates;
        let diff = (nextTot - (row.New + row.Updates)) / nextTot;
        yoy = diff.toFixed(2) + "%"; // or whatever format
      }
      
      return <tr key={index}>
        <td>{row.Years}</td>
        <td>{row.New}</td>
        <td>{row.Updates}</td>
        <td>{row.New + row.Updates}</td>
        <td>{parsedAdmin2ReportData[index].New}</td>
        <td>{yoy}</td>
      </tr>
    }
    ))}
    </tbody>