diff --git a/packages/nodes-base/nodes/Transform/Summarize/test/unitTests/splitData.test.ts b/packages/nodes-base/nodes/Transform/Summarize/test/unitTests/splitData.test.ts index 2c531dad77c..211b52c3223 100644 --- a/packages/nodes-base/nodes/Transform/Summarize/test/unitTests/splitData.test.ts +++ b/packages/nodes-base/nodes/Transform/Summarize/test/unitTests/splitData.test.ts @@ -311,4 +311,32 @@ describe('Test Summarize Node, aggregateAndSplitData', () => { expect(flattenAggregationResultToArray(result)).toMatchSnapshot('array'); }); }); + + test('should return null, not NaN, for the average of a group with no numeric values', () => { + const data = [ + { Sku: 'A', Qty: 2, _itemIndex: 0 }, + { Sku: 'A', Qty: 4, _itemIndex: 1 }, + { Sku: 'B', Qty: 'n/a', _itemIndex: 2 }, + { Sku: 'B', Qty: '', _itemIndex: 3 }, + ]; + + const aggregations: Aggregations = [ + { aggregation: 'average', field: 'Qty' }, + { aggregation: 'sum', field: 'Qty' }, + ]; + + const result = aggregateAndSplitData({ + splitKeys: ['Sku'], + inputItems: data, + fieldsToSummarize: aggregations, + options: { continueIfFieldNotFound: true }, + getValue: fieldValueGetter(), + }); + + // Sum keeps returning 0, the identity for a sum, for a group with no numeric values. + expect(flattenAggregationResultToArray(result)).toEqual([ + { returnData: { Sku: 'A', average_Qty: 3, sum_Qty: 6 }, pairedItems: [0, 1] }, + { returnData: { Sku: 'B', average_Qty: null, sum_Qty: 0 }, pairedItems: [2, 3] }, + ]); + }); }); diff --git a/packages/nodes-base/nodes/Transform/Summarize/utils.ts b/packages/nodes-base/nodes/Transform/Summarize/utils.ts index 5347ed610b8..ba628245f8c 100644 --- a/packages/nodes-base/nodes/Transform/Summarize/utils.ts +++ b/packages/nodes-base/nodes/Transform/Summarize/utils.ts @@ -122,6 +122,11 @@ function aggregate(items: IDataObject[], entry: Aggregation, getValue: ValueGett //numerical operations case 'average': + // No numeric values to average: report null like min and max do, + // instead of the NaN that 0 / 0 would give. + if (data.length === 0) { + return null; + } return ( data.reduce((acc, item) => { return acc + (getValue(item, field) as number);