Skip to content

Instantly share code, notes, and snippets.

@snth
Last active November 27, 2024 10:25
Show Gist options
  • Save snth/2f105223b72a94828abf5979ceac379f to your computer and use it in GitHub Desktop.
Save snth/2f105223b72a94828abf5979ceac379f to your computer and use it in GitHub Desktop.
XMAP - Enhanced Array Mapping Function for Excel (AFE/Excel Labs)
/*
XMAP
Applies a function to each row, column, or element of an array, with configurable mapping dimension.
Like MAP() but with added flexibility for handling multi-dimensional arrays.
Inputs:
- array: The input array to map over
- function: The function to apply to each row/column/element
- dimension (optional): Controls how the function is applied:
0 = Apply to each element (same as MAP)
1 = Apply to each row
2 = Apply to each column
If omitted, automatically chooses based on array shape:
- For single column arrays: dimension=1 (map over rows)
- For single row arrays: dimension=2 (map over columns)
- Otherwise: dimension=0 (map over elements)
Return:
A new array where the function has been applied according to the specified dimension.
The result shape depends on the function's output and chosen dimension.
Examples:
=XMAP(A1:D4, LAMBDA(x,SUM(x)), 1) ' Sums each row
=XMAP(A1:D4, LAMBDA(x,SUM(x)), 2) ' Sums each column
=XMAP(A1:D4, LAMBDA(x,x*2)) ' Doubles each element
Note:
The function parameter should accept a single argument which will be:
- A single value when dimension=0
- A row array when dimension=1
- A column array when dimension=2
*/
XMAP = LAMBDA(array, function, [dimension],
LET(
_dim, IFS(
NOT(ISOMITTED(dimension)),
dimension,
COLUMNS(array) = 1,
1,
ROWS(array) = 1,
2,
TRUE,
0
),
_unwrap, LAMBDA(_v, IF(ROWS(_v)*COLUMNS(_v)=1, @_v, _v)),
_make_mapper, LAMBDA(_counter, _chooser, _stacker, _flattener,
LAMBDA(_array, _function,
IF(
_counter(_array) = 1,
_flattener(_function(_unwrap(_chooser(_array, 1)))),
REDUCE(
_flattener(_function(_unwrap(_chooser(_array, 1)))),
SEQUENCE(_counter(_array) - 1, 1, 2),
LAMBDA(_acc, _i,
_stacker(
_acc,
_flattener(
_function(_unwrap(_chooser(_array, _i)))
)
)
)
)
)
)
),
_mapper, SWITCH(
_dim,
0, MAP,
1, _make_mapper(ROWS, CHOOSEROWS, VSTACK, TOROW),
2, _make_mapper(COLUMNS, CHOOSECOLS, HSTACK, TOCOL),
NA()
),
_result, _mapper(array, function),
_result
)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment