2021-11-03 02:54:09 +00:00
|
|
|
# Group By
|
|
|
|
|
2021-10-26 04:07:50 +00:00
|
|
|
This is used to group items in an array by an expression.
|
|
|
|
|
|
|
|
## Group by field
|
|
|
|
Given a sample.yml file of:
|
|
|
|
```yaml
|
2023-05-05 05:19:58 +00:00
|
|
|
[{foo: 1, bar: 10}, {foo: 3, bar: 100}, {foo: 1, bar: 1}]
|
2021-10-26 04:07:50 +00:00
|
|
|
```
|
|
|
|
then
|
|
|
|
```bash
|
2022-01-27 06:21:10 +00:00
|
|
|
yq 'group_by(.foo)' sample.yml
|
2021-10-26 04:07:50 +00:00
|
|
|
```
|
|
|
|
will output
|
|
|
|
```yaml
|
2023-05-05 05:19:58 +00:00
|
|
|
- - [{foo: 1, bar: 10}, {foo: 3, bar: 100}, {foo: 1, bar: 1}]
|
|
|
|
- [{foo: 1, bar: 10}, {foo: 3, bar: 100}, {foo: 1, bar: 1}]
|
|
|
|
- - [{foo: 1, bar: 10}, {foo: 3, bar: 100}, {foo: 1, bar: 1}]
|
2021-10-26 04:07:50 +00:00
|
|
|
```
|
|
|
|
|
|
|
|
## Group by field, with nuls
|
|
|
|
Given a sample.yml file of:
|
|
|
|
```yaml
|
2023-05-05 05:19:58 +00:00
|
|
|
[{cat: dog}, {foo: 1, bar: 10}, {foo: 3, bar: 100}, {no: foo for you}, {foo: 1, bar: 1}]
|
2021-10-26 04:07:50 +00:00
|
|
|
```
|
|
|
|
then
|
|
|
|
```bash
|
2022-01-27 06:21:10 +00:00
|
|
|
yq 'group_by(.foo)' sample.yml
|
2021-10-26 04:07:50 +00:00
|
|
|
```
|
|
|
|
will output
|
|
|
|
```yaml
|
2023-05-05 05:19:58 +00:00
|
|
|
- - [{cat: dog}, {foo: 1, bar: 10}, {foo: 3, bar: 100}, {no: foo for you}, {foo: 1, bar: 1}]
|
|
|
|
- [{cat: dog}, {foo: 1, bar: 10}, {foo: 3, bar: 100}, {no: foo for you}, {foo: 1, bar: 1}]
|
|
|
|
- - [{cat: dog}, {foo: 1, bar: 10}, {foo: 3, bar: 100}, {no: foo for you}, {foo: 1, bar: 1}]
|
|
|
|
- [{cat: dog}, {foo: 1, bar: 10}, {foo: 3, bar: 100}, {no: foo for you}, {foo: 1, bar: 1}]
|
|
|
|
- - [{cat: dog}, {foo: 1, bar: 10}, {foo: 3, bar: 100}, {no: foo for you}, {foo: 1, bar: 1}]
|
2021-10-26 04:07:50 +00:00
|
|
|
```
|
|
|
|
|