Skip to content

group_by

Groups the elements of items by the key returned by key.

Within each group, elements keep their original order. The order of the groups themselves is unspecified (HashMap).

use helpers4::array::group_by;

Cargo feature array (enabled by default). To compile only this module:

cargo add helpers4 --no-default-features --features array

or in Cargo.toml:

[dependencies]
helpers4 = { version = "0.0.5", default-features = false, features = ["array"] }
pub fn group_by<T: Clone, K: Eq + Hash>(
    items: &[T],
    mut key: impl FnMut(&T) -> K,
) -> HashMap<K, Vec<T>>
ParameterTypeDescription
items&[T]The elements to group.
keyimpl FnMut(&T) -> KReturns the key to group each element under.

HashMap<K, Vec<T>>

use helpers4::array::group_by;

let groups = group_by(&[1, 2, 3, 4, 5], |n| n % 2 == 0);
assert_eq!(groups[&true], vec![2, 4]);
assert_eq!(groups[&false], vec![1, 3, 5]);

src/array/group_by.rs