How to get the unique values of an array in Rust

1 Answer

0 votes
use std::collections::HashSet;

fn get_unique_values(arr: &[i32]) -> Vec<i32> {
    let set: HashSet<_> = arr.iter().cloned().collect();
    
    set.into_iter().collect()
}

fn main() {
    let array = [1, 2, 1, 1, 3, 3, 4, 4, 5, 5, 5, 5, 6, 7, 7, 8];
    
    let unique = get_unique_values(&array);
    
    println!("{:?}", unique);
}


/*
run:

[2, 3, 7, 1, 4, 6, 5, 8]

*/

 



answered Feb 19, 2025 by avibootz
...