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.
Transform Map values
Section titled “Transform Map values”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 . * 2def expensive = prices ifv . > 2doubled_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)// }Reduce a Bag
Section titled “Reduce a Bag”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.
Group repeated keys
Section titled “Group repeated keys”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}Build a sales summary
Section titled “Build a sales summary”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)// }ifkeeps sales with an amount above1.bygives each sale its category as a key.aggvcounts the sales and adds their amounts for each category.
Quick reference
Section titled “Quick reference”| 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 |