Skip to content
Open Saka

Grouping and summarizing

Maps let you group data by a key, such as a sale’s category. These examples use sales from the previous page.

mapv changes a Map’s value and keeps its key. ifv tests the value:

def prices = {"pen" -> 2, "book" -> 5}
def doubled_prices = prices mapv . * 2
def expensive = prices ifv . > 2
doubled_prices // {"book" -> 10, "pen" -> 4}
expensive // {"book" -> 5}

. means the value; .. means the key:

def labeled = prices mapv (name: .., price: .)
labeled
// {
// "book" -> (name: "book", price: 5)
// "pen" -> (name: "pen", price: 2)
// }

A reducer summarizes a whole Bag. Repeats count:

count({1, 2'2}) // {3}
sum({1, 2'2}) // {5}

The reference below lists the other reducers.

aggv groups equal keys and runs once per group. Inside it, .. is the key and . is the Bag of values:

def counts = sales by .category aggv count(.)
counts // {"a" -> 2, "b" -> 2}

Combine filtering, keying, and grouping:

def summary = sales if .amount > 1 by .category
aggv (sales: count(.), total: sum(.amount))
summary
// {
// "a" -> (sales: 2, total: 5)
// "b" -> (sales: 1, total: 4)
// }
  1. if keeps sales with an amount above 1.
  2. by gives each sale its category as a key.
  3. aggv counts the sales and adds their amounts for each category.
Reducer Summary Empty input
count Number of occurrences {0}
min Smallest Value Empty Bag
max Largest Value Empty Bag
all Are all Values true? {true}
any Is any Value true? {false}
sum Total, including repeats {0}
avg Average, including repeats Empty Bag