@@ -277,7 +277,9 @@ export function computePivot<T extends Record<string, unknown>>({
277277
278278 // Deterministic ordering
279279 rowKeyTuples . sort ( ( a , b ) => toKey ( a ) . localeCompare ( toKey ( b ) ) ) ;
280- colKeyTuples . sort ( ( a , b ) => toKey ( a ) . localeCompare ( toKey ( b ) ) ) ;
280+
281+ // Sort columns by aggregate score (largest to smallest) instead of alphabetically
282+ // We'll sort after calculating column totals, so we'll do it later
281283
282284 type CellAgg = { value : number ; records : T [ ] } ;
283285 const cells : Record < string , Record < string , CellAgg > > = { } ;
@@ -357,6 +359,16 @@ export function computePivot<T extends Record<string, unknown>>({
357359 colTotals [ cKey ] = aggregate ( columnValues , columnRecords , aggregator ) ;
358360 }
359361
362+ // Sort columns by aggregate score (largest to smallest) based on column totals
363+ colKeyTuples . sort ( ( a , b ) => {
364+ const aKey = toKey ( a ) ;
365+ const bKey = toKey ( b ) ;
366+ const aTotal = colTotals [ aKey ] ?? 0 ;
367+ const bTotal = colTotals [ bKey ] ?? 0 ;
368+ // Sort from largest to smallest (descending order)
369+ return bTotal - aTotal ;
370+ } ) ;
371+
360372 // Grand total should follow the same aggregation semantics over the entire dataset
361373 // rather than summing per-row/per-column aggregates (which can be incorrect for
362374 // non-additive aggregations like "avg").
0 commit comments