How to get the sum of a column in a table component

I have a column of integer type and simply want to get the sum of all the values in the column. Is there a really simple way to do this?

How about this?

Here is the default table and a number component. In the number component I have the Default value as

{{table1.data.unit_price_cents.reduce((x,y)=>x+y,0)}}

This will sum the column of the table data!

Hope this helps.

Jeremy

1 Like

@jclutterbuck

Thank you that's very helpful. I think that would normally work but the column I am trying to add is a custom made column. Is this possible?

At the moment custom columns can be thought of as being display-only. Depending on how you're using the custom column you might, instead, add the column to your table data via a transformer before passing it to the component itself, that way you can access it as part of yourTable.data. Otherwise, you can copy the column logic into the aggregator.

Let's say the value of your custom column was something like {{ currentRow.unit_price * currentRow.units_sold }}. To add it as a regular column via a transformer you could do something like:

{{ formatDataAsArray(table1.data).map(row => ({...row, total_sold: row.unit_price * row.units_sold})) }}

If you were to use the reducer you could try:

{{ table1.data.unit_price.reduce((x, y, index) => x + y * table1.data.units_sold[i], 0) }}

Let me know if that works!

1 Like