Example 1 — Official Meals by Type
Group five meals by their type — the sample from the Ramda docs.
const meals = [
{ type: 'breakfast', item: 'coffee' },
{ type: 'lunch', item: 'burrito' },
{ type: 'dinner', item: 'pasta' },
{ type: 'breakfast', item: 'croissant' },
{ type: 'lunch', item: 'pizza' }
];
const groups = R.collectBy(R.prop('type'), meals);
groups.forEach((group) => console.log(group)); How It Works
- Key.
R.prop('type')reads each meal’s type: breakfast, lunch, dinner, breakfast, lunch. - Bucket. Meals with the same type go into the same sub-list.
- Order. Breakfast comes first because it was seen first; inside each group, meals keep their list order.
- Result. Three groups come back as an array; the words “breakfast”, “lunch”, and “dinner” are not included.
