pub fn group_by<T, K, F>(items: Vec<T>, key_fn: F) -> HashMap<K, Vec<T>>Expand description
Group items by a key extraction function. Returns a HashMap where keys are the result of the key function and values are vectors of items.
ยงExamples
use chie_shared::group_by;
// Group numbers by their remainder when divided by 3
let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
let groups = group_by(numbers, |n| n % 3);
assert_eq!(groups[&0], vec![3, 6, 9]);
assert_eq!(groups[&1], vec![1, 4, 7]);
assert_eq!(groups[&2], vec![2, 5, 8]);
// Group strings by their first character
let words = vec!["apple", "apricot", "banana", "berry", "cherry"];
let by_first = group_by(words, |w| w.chars().next().unwrap());
assert_eq!(by_first[&'a'].len(), 2);
assert_eq!(by_first[&'b'].len(), 2);
assert_eq!(by_first[&'c'].len(), 1);