Grouping Data
Overview
Grouping data refers to the process of taking an array of objects, and then splitting that array into multiple groups,
where the items of a group share some property.
As an example, consider the following records.
These records may represent the incomes of employees in a company and each employees age. You may wish to
view the distribution of incomes by age, which means you want to group all the records according to age.
The $group api provides a method to group the records by a given column.
let data = [{age:40, income:100000},{age:30, income:40000},{age:40, income:56000},{age:32, income:100000},{age:35, income:100000}, ];
let groups = $group(data, p=>p.age);
Try it
groups will now be a dictionary where the keys are the values of the ages in the original array. The values
associated with each key is an array of the items that have that age. Then, to retrieve an array of items
with an age of 40, you could execute the following call.
To return the groupings as an object or map, one can simply call the gropus function with no arguments.
Using Computed Group Criteria
Groupings dont necessarily have to use a specific property of the items being grouped. For example, you could group
by a computed value. For example, the following groups the set of price data by month. This code uses the split method
of the string object to split the date into 3 fields, and then returns the second field (which is the month).
let data = [{date:'2000-01-01', price:100},{date:'2000-01-10', price:100},{date:'2000-01-31', price:100},{date:'2000-02-01', price:100},{date:'2000-02-10', price:100}, ];
let groups = $list(data).group(p=>p.date.split('-')[1]).object;
Try it
Groups as a List
When you do a grouping using the $list api, you get a Javascript dicitionary out of it. However, you can
transform this back to a list by using the toList method.
let data = [{age:40, income:100000},{age:30, income:40000},{age:40, income:56000},{age:32, income:100000},{age:35, income:100000}, ];
let groups = $list(data).group(p=>p.age).toList();
Try it
This creates a list of records with two properties, a keys property and a values property.
For example, the record with the age value of 40 would be given as follows.
{keys:[40], values:[{age:40, income:100000},{age:40, income:56000},]}
Try it
Notice that the keys value is an array, despite the fact that only one key was used in the grouping. This is to
accomodate groupings that are based on multiple keys (see above).