Docs / Learn mapping / Mapper Grouping and Ordering

Group and order lines and mapped records

Use groupBy when several source records belong to one business result, and orderBy when the receiver needs a particular sequence. Both retain the original items. This guide explains their collection shapes and key rules; the interactive lesson provides staged practice.

Understand the dictionary of buckets

groupBy(item in source => key) computes a text key for each item and returns a dictionary. Every dictionary value is a list containing the original items, not their projected keys. For these mapped records:

lines=[{"sku":"B200","quantity":2},{"sku":"A100","quantity":1},{"sku":"B200","quantity":3}]
toJson(groupBy(line in lines => line["sku"]))
// {"B200":[{"sku":"B200","quantity":2},{"sku":"B200","quantity":3}],"A100":[{"sku":"A100","quantity":1}]}

Buckets follow the order their keys are first seen, so B200 precedes A100 here. Items inside each bucket stay in source order, including duplicates. An empty source produces {}. An optional predicate after : filters items before their keys are computed.

Read each bucket and build a summary

Iterating the dictionary exposes one entry at a time. key(group) reads its SKU; val(group) reads its list of records. Summing a bucket is a separate projection:

lines=[{"sku":"B200","quantity":2},{"sku":"A100","quantity":1},{"sku":"B200","quantity":3}]
groups=groupBy(line in lines => line["sku"])
toJson(forEach(group in groups => {
    "sku":key(group),
    "quantity":sumOf(line in val(group) => line["quantity"])
}))
// [{"sku":"B200","quantity":5},{"sku":"A100","quantity":1}]

This example assumes compatible units and business context. Group by every field that determines whether records can be combined. If the same SKU can appear in EA and CS, include the unit: groupBy(line in lines => toJson([line["sku"],line["unit"]])). A JSON list gives an unambiguous composite key; concatenating fields with an ordinary delimiter can collide. Preserve separate orders or other required distinctions in the key too.

Keys use text conversion and match case-sensitively. Numeric 1 and text "1" share a bucket, while numeric 1.0 uses "1.0". Normalize deliberately when different spellings should match. Grouping original X12 segments retains their navigation: within val(group), a PO1 still supports line(02). Serializing a segment itself produces its name, such as "PO1"; project its fields to inspect meaningful business values.

Before grouping X12 quantities, require the fields that make each total meaningful: required(line(02),"Quantity (PO102) is required before grouping.") and required(line(03),"Unit (PO103) is required before grouping."). An absent quantity is not a transmitted zero, and a missing unit cannot establish compatibility. required rejects an empty selection with E2801 while preserving an explicit numeric zero. See missing values and defaults.

Check quantities and units in typed records

When you already have typed records, check the fields before grouping. This example keeps a recorded quantity of zero.

lines = [{"sku":"A100","unit":"EA","quantity":0}]
toJson(forEach(line in lines => {
    "sku":line["sku"],
    "unit":required(line["unit"], "Unit is required before grouping."),
    "quantity":required(line["quantity"], "Quantity is required before grouping.")
}))

Remove the quantity and run it again to see the quantity error. Restore the zero, remove the unit, and run it to see the unit error. Both conditions report E2801. These omissions can occur independently in typed records. In a 004010 850, supplying any of PO102, PO103, or PO104 requires the other two, so the lesson tests a line where all three are absent.

Choose a sorting key and direction

toJson(orderBy(value in [10,2,1] => value))
// [1,2,10]
toJson(orderBy(code in ["A","C","B"] => code,"desc"))
// ["C","B","A"]

The expression after => computes the sorting key. The result is a new list containing the original items. Ascending order is the default; the optional second argument accepts "asc" or "desc".

Equal keys keep their original order in both directions. Numeric 1 and 1.0, for example, tie. Duplicates remain in the result.

Sort PO1 lines, then read their fields

A purchase order may list lines in a different order from their line numbers. PO101 is text, so convert it explicitly when the partner uses numeric line numbers.

Open salesOrder.map in the Mapper demo. In the starter 850 input, change PO1*1* to PO1*20* and PO1*3* to PO1*10*. Replace the map source with the example below and choose Run map.

lines=orderBy(line in ST->PO1 => toNumber(line(01)))
toJson(forEach(line in lines => {
    "line":line(01),
    "quantity":line(02),
    "description":line->PID(05)
}))

Line numbers 20, 2, and 10 become 2, 10, and 20. Each item remains a segment: line(02) still reads its quantity and line->PID(05) still reads its associated description. Sorting by quantity instead can use the numeric X12 element directly: orderBy(line in ST->PO1 => line(02),"desc").

Order consolidated SKU totals

Grouping has already produced the two summary records shown above. Sorting those records is a separate decision; here the receiver needs SKU order:

totals=[{"sku":"B200","quantity":5},{"sku":"A100","quantity":1}]
toJson(orderBy(total in totals => total["sku"]))
// [{"sku":"A100","quantity":1},{"sku":"B200","quantity":5}]

The same pattern works for other mapped records. Consistently formatted YYYY-MM-DD text dates sort chronologically:

deliveries=[{"date":"2026-10-06","quantity":50},{"date":"2026-10-02","quantity":20}]
toJson(orderBy(delivery in deliveries => delivery["date"]))
// [{"date":"2026-10-02","quantity":20},{"date":"2026-10-06","quantity":50}]

Use consistently numeric or text keys

Every key in one call must be a number, or every key must be text. Numbers sort numerically. Text sorts case-sensitively by UTF-16 code units, without locale collation: "10" comes before "2". Use toNumber(...) for numeric text or toLower(...) for case-insensitive text keys.

A one-item list containing a number or string, or a selection containing exactly one X12 element, is unwrapped once to its numeric value or text. Empty lists, multi-item lists, nested lists, dictionaries, booleans, null, and segments cannot serve as keys. Unwrapping does not turn numeric-looking text into a number. Empty text is a valid key and comes first in ascending order. Choose an explicit default for a missing sort value; see null and defaults.

Text functions preserve their input shape: toLower(line(01)) returns a one-item text list for one selected line number. orderBy accepts that key directly while retaining the original segments and their original capitalization:

toJson(forEach(line in
    orderBy(line in ST->PO1 => toLower(line(01)))
    => line(01)
))

For line identifiers a, B, and c, this returns ["a","B","c"]. Equal normalized keys retain source order. The singleton rule applies to the sorting key; it does not flatten lists in the returned items or change how text functions and JSON serialization preserve lists.

Use the optional predicate after : to omit records before computing their keys. For example, skip empty text before numeric conversion:

toJson(orderBy(value in ["10","","2"] : !isEmpty(value) => toNumber(value)))
// ["2","10"]

The values remain strings because only the key is converted. For missing optional elements, use a filter or an explicit fallback such as firstNonEmpty(...). The source is evaluated once, then each predicate and matching item's key is evaluated in source order. The direction is evaluated once afterward. The iterator is local to the predicate and key; the source and direction use the outer scope.

Compose with other collections

Sources may be segment paths, element selections, lists, dictionaries, or expressions that return those collections. Empty sources and filters with no matches produce []. Required path assertions still apply: ST->N1->N3! and ST->N1->N3+ report E2604 when no N1 exists, since the required descendant has no matches. Use ? or an unsuffixed path when an empty result is acceptable. Feed the ordered list to forEach, find, sumOf, groupBy, or flatMap.

A dictionary source contributes one-entry dictionaries. Use key(entry) and val(entry) in the sorting expression:

toJson(orderBy(entry in {"b":2,"a":1} => key(entry)))
// [{"a":1},{"b":2}]

When iterating the resulting list, key(item) is the new list index. Assign entry=item inside that loop to read the stored dictionary key with key(entry).

Sorting creates a new outer list, so changing its order or replacing an item does not modify the source list. Nested lists and dictionaries remain shared: editing a nested record changes that same record in both places. Element-source items become scalar values that keep their numeric type and original text formatting; segment-source items retain their segment navigation.

Resolve sorting errors

  • E4701: The key does not contain exactly one number or text value. For orderBy(n in [1] => [n,n]), select one key with => n or => [n]. Empty and nested lists also fail.
  • E4702: Numeric and text keys are mixed. For orderBy(n in [1,"2"] => n), use => toNumber(n) if numeric order is intended.
  • E4703: The direction is not "asc" or "desc". For orderBy(n in [1] => n,"down"), replace "down" with "desc".

Practice grouping in stages in Summarize, group, and sort order lines, then save the expected result as a mapping test case. The Mapper Built-ins reference includes the complete signature, examples, and error guidance.