Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter a vector using a boolean array

Tags:

rust

How do I use the boolean_arr to filter ys based on the bool values?

The arrays all have the same length.

fn main() {
    let xs: Vec<f32> = vec![300., 7.5, 10., 250.];
    let boolean_arr: Vec<bool> = xs.into_iter().map(|x| x > 10.).collect();

    let ys: Vec<f32> = vec![110.5, 50., 25., 770.];

    assert_eq!(wanted_vec, vec![110.5, 770.]);
}
like image 588
user270199 Avatar asked Sep 03 '25 03:09

user270199


1 Answers

We can use zip to combine the two and then filter the results. Here's a general-purpose function that works on arbitrary iterators.

fn filter_by<I1, I2>(bs: I1, ys: I2) -> impl Iterator<Item=<I2 as Iterator>::Item>
where I1: Iterator<Item=bool>,
      I2: Iterator {
  bs.zip(ys).filter(|x| x.0).map(|x| x.1)
}

And how to call it in your particular use case

let wanted_vec: Vec<_> = filter_by(boolean_arr.into_iter(), ys.into_iter()).collect();
like image 61
Silvio Mayolo Avatar answered Sep 04 '25 20:09

Silvio Mayolo