SRugina
SRugina

Reputation: 149

Is there a way to convert a `Vec<Vec<T>>` to `Vec<T>`, combining all the `Vec<T>`s into one `Vec<T>`?

Let's say I have a Vector of Organisation ids

let orgs = vec![1, 3, 14, 12];

I then call .iter() on each to get the events of each organisation, where the function get_events_for() returns Vec<Event>

let events = orgs
    .iter()
    .map(|org_id| {
        get_events_for(org_id)
    })
    .collect();

Currently, events is equal to Vec<Vec<Event>>, so how would one go about converting that to just Vec<Event>?

Upvotes: 1

Views: 185

Answers (2)

fmendez
fmendez

Reputation: 7338

This is what a more complete implementation would look like using some of the answers already given here:

#[derive(Debug)]
struct Event {
    id: usize
}

fn main() {
  let orgs = vec![1, 3, 14, 12];

  let events: Vec<Event> = orgs
    .iter()
    .flat_map(|org_id| {
        get_events_for(*org_id)
    })
    .collect();

  println!("{:?}", events);

}

fn get_events_for(id: usize) -> Vec<Event> {
   vec![Event {id}]
}

The output would look like:

[Event { id: 1 }, Event { id: 3 }, Event { id: 14 }, Event { id: 12 }]

Playground

Upvotes: 2

Ry-
Ry-

Reputation: 224845

flat_map:

let events = orgs
    .iter()
    .flat_map(get_events_for)
    .collect();

Upvotes: 3

Related Questions