pub fn flat_map<T, R, F>(collection: &[T], iteratee: F) -> Vec<R>Expand description
Apply a function to each item in a collection, flattening the results based on a callback.
This function iterates over a collection and applies the provided iteratee function
to each item along with its index. The iteratee returns a vector of transformed items,
which are then concatenated into a single resulting vector.
§Arguments
collection- A slice of items.iteratee- A function that takes a reference to an item and its index, returning a vector of transformed items.
§Returns
Vec<R>- A vector containing all the transformed items from each iteration.
§Examples
use lowdash::flat_map;
let numbers = vec![1, 2, 3];
// For each number, generate a vector containing the number and its double
let result = flat_map(&numbers, |x, _| vec![*x, *x * 2]);
assert_eq!(result, vec![1, 2, 2, 4, 3, 6]);use lowdash::flat_map;
#[derive(Debug, PartialEq)]
struct Person {
name: String,
hobbies: Vec<String>,
}
let people = vec![
Person {
name: "Alice".to_string(),
hobbies: vec!["Reading".to_string(), "Cycling".to_string()],
},
Person {
name: "Bob".to_string(),
hobbies: vec!["Cooking".to_string()],
},
];
// Extract all hobbies from the list of people
let all_hobbies: Vec<String> = flat_map(&people, |person, _| person.hobbies.clone());
assert_eq!(
all_hobbies,
vec![
"Reading".to_string(),
"Cycling".to_string(),
"Cooking".to_string()
]
);