Skip to content

unique_by

Removes elements whose key was already seen, keeping the first of each key in order.

use helpers4::array::unique_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 unique_by<T: Clone, K: Eq + Hash>(items: &[T], mut key: impl FnMut(&T) -> K) -> Vec<T>
ParameterTypeDescription
items&[T]The elements to deduplicate.
keyimpl FnMut(&T) -> KReturns the key that decides which elements are duplicates.

Vec<T>

use helpers4::array::unique_by;

let words = ["apple", "avocado", "banana", "blueberry", "cherry"];
assert_eq!(
    unique_by(&words, |w| w.chars().next()),
    vec!["apple", "banana", "cherry"]
);

src/array/unique_by.rs