Count and Aggregation
$count() is the primary aggregation function in DAQS rules. It counts how many items are in an array, which enables duplicate detection, completeness checks, and conditional output.
$count() — count items in an array
$count([1, 2, 3]) /* 3 */
$count([]) /* 0 */
$count("hello") /* 1 — single values count as 1 */
$count(undefined) /* 0 */
Pass a filter expression to count elements matching a condition:
$count($[type = "FamilyInstance"])
Detecting duplicates
The most common use of $count() in DAQS rules is checking how many other elements share the same value. If the count is greater than zero, the element has a duplicate.
(
$rooms := $[type = "Room"];
$countDuplicates := function($number, $id) {
$count($rooms[values.number = $number and id != $id])
};
$rooms.{
"id": id,
"name": name,
"number": values.number,
"duplicateCount": $countDuplicates(values.number, id)
}
)
Each room gets a duplicateCount field. The validator then checks duplicateCount = 0.
The function excludes the element itself (id != $id) so a room does not count as its own duplicate.
Using $count() as a guard condition
$count() is often used inside a ternary (condition ? a : b) to handle the case where a filter returns nothing:
$count($[type = "Level"]) > 0
? $[type = "Level"].id
: null
This prevents downstream errors when the filtered array is empty.
$count() vs checking for null
| Goal | Expression |
|---|---|
| Is the array non-empty? | $count($arr) > 0 |
| Is a field filled in? | $exists(values.mark) and values.mark != null |
| Did a filter return results? | $count($filter) > 0 |
Use $exists() to check whether a field is present at all. Use $count() to check whether a collection has items.
$sum() — sum numeric values in an array
$sum() adds up all values in an array of numbers:
$sum([1, 2, 3]) /* 6 */
$sum([]) /* 0 */
It is most useful in combination with $map() to reduce an array of objects to a total:
$sum($map($items, function($item) {
$item.count
}))
Checking array membership with $sum + $map
There is no built-in $contains() for arrays in JSONata. The standard workaround is to map over the array, score each element as 1 or 0, and sum the result:
$arrayContains := function($array, $v) {
$exists($array) and $array != null
? $sum($map($array, function($item) { $item = $v ? 1 : 0 })) > 0
: false
};
$arrayContains(["a", "b", "c"], "b") returns true.
This pattern appears in production rules that check whether a value is in a computed array (not a static list, where the in operator is simpler — see In Operator).
Common mistakes
- Relying on
$count()on a non-array — a single matched object (not wrapped in[]) returns1, which can look correct even when the intent was to check an array - Forgetting to exclude self (
id != $id) in duplicate detection — every element would count itself and always reportduplicateCount >= 1 - Using
$sum()on an array that containsnullorundefined— JSONata treats non-numbers as0, so the result is still a number, not an error