group_by

Function group_by 

Source
pub fn group_by<T, U, F>(collection: &[T], iteratee: F) -> HashMap<U, Vec<T>>
where T: Clone, U: Eq + Hash + Clone, F: Fn(&T) -> U,
Expand description

Group elements of a collection based on a key extracted by a provided function, preserving the order of their first occurrence.

This function takes a slice of items and returns a HashMap<U, Vec<T>> where each key corresponds to a group of items that share the same key.

Note: This implementation requires U to implement Hash, Eq, and Clone, and T to implement Clone.

§Arguments

  • collection - A slice of items to be grouped.
  • iteratee - A function that takes a reference to an item and returns a key of type U.

§Type Parameters

  • T - The type of elements in the collection. Must implement Clone.
  • U - The type of the key extracted from each element used to group the elements. Must implement Hash, Eq, and Clone.
  • F - The type of the iteratee function. Must implement Fn(&T) -> U.

§Returns

  • HashMap<U, Vec<T>> - A map where each key is associated with a vector of items that share the same key.

§Examples

use lowdash::group_by;

let numbers = vec![1, 2, 2, 3, 4, 3, 5];
let grouped = group_by(&numbers, |x| *x % 2 == 0);

assert_eq!(grouped.get(&false), Some(&vec![1, 3, 3, 5]));
assert_eq!(grouped.get(&true), Some(&vec![2, 2, 4]));
use lowdash::group_by;

#[derive(Debug, PartialEq, Clone)]
struct Person {
    name: String,
    age: u32,
}

let people = vec![
    Person { name: "Alice".to_string(), age: 25 },
    Person { name: "Bob".to_string(), age: 30 },
    Person { name: "Carol".to_string(), age: 25 },
];

let grouped = group_by(&people, |p| p.age);

assert_eq!(grouped.get(&25), Some(&vec![
    Person { name: "Alice".to_string(), age: 25 },
    Person { name: "Carol".to_string(), age: 25 },
]));
assert_eq!(grouped.get(&30), Some(&vec![
    Person { name: "Bob".to_string(), age: 30 },
]));