[Bug] AVERAGE returns a single element of FILTER/SORT/UNIQUE or arithmetic array results
Before you submit this issue, have you checked the following
- Is this really a problem?
- I have searched the Github Issues for similar issues, but did not find anything.
Affected packages and versions
@univerjs/engine-formula 1.0.2 (also present on dev at 974b8a8cd)
Reproduction link
AVERAGE over an array returned by another function (FILTER, SORT, UNIQUE, an arithmetic expression, ...) returns a single element of that array instead of averaging all of it.
| A | B | C | |
|---|---|---|---|
| 1 | Phone | 0 | 3 |
| 2 | Laptop | 0.5 | 5 |
| 3 | Phone | 0.1 | 7 |
Results with the formula entered in H1 and in H3:
| Formula | Univer in H1 | Univer in H3 | Excel 365 |
|---|---|---|---|
=AVERAGE(FILTER(C1:C3,A1:A3="Phone")) |
3 |
3 |
5 |
=AVERAGE(FILTER(B1:B3,A1:A3="Phone")) |
0 |
0.05 |
|
=AVERAGE(SORT(C1:C3,1,-1)) |
7 |
7 |
5 |
=AVERAGE(UNIQUE(C1:C3)) |
3 |
3 |
5 |
=AVERAGE(C1:C3*2) |
6 |
14 |
10 |
=AVERAGE(C1:C3+0) |
3 |
7 |
5 |
=SUM(C1:C3+0) |
15 |
15 |
15 |
=SUM(FILTER(C1:C3,A1:A3="Phone")) |
10 |
10 |
|
=AVERAGE({3;7}) |
5 |
5 |
SUM, COUNT, MAX and INDEX over the same arrays are correct; only AVERAGE is wrong, and for arithmetic arrays its result depends on which row the formula is in.
I found this while running formulas generated by iFlytek Spark-X2.5 against a headless Univer workbook. The model wrote =AVERAGE(FILTER($F$2:$F$9,$B$2:$B$9="Phone")) for an "average discount of phones" question, and Univer returned the first matching discount instead of the average.
Expected behavior
AVERAGE averages every numeric value of an array argument, as in Excel 365 and as SUM already does.
Actual behavior
Average._legacyImplicitDerivedArray (packages/engine-formula/src/functions/statistical/average/index.ts) applies implicit intersection to any array that carries a position (getCurrentRow() / getCurrentColumn() >= 0). It then replaces the whole array with the element at the formula's row or column. Sum._legacyImplicitDerivedArray has the same helper but only applies it when array.usesLegacyImplicitForAggregate() is set, which ArrayValueObject sets only for the legacy PLUS batch operation. AVERAGE is missing that guard.
System information
Node.js 24.16.0, Windows 11
Source: dream-num/univer