pub fn compact<T>(collection: &[T]) -> Vec<T>Expand description
Removes all zero-valued elements from a collection, preserving the order of non-zero elements.
This function iterates over a slice of items, removing each element that is equal to the zero value.
The zero value is determined by the Default trait implementation for the type T.
The function preserves the order of the remaining elements and does not modify the original collection.
Time Complexity: O(n), where n is the number of elements in the collection.
§Arguments
collection- A slice of items from which to remove zero-valued elements.
§Type Parameters
T- The type of elements in the collection. Must implementPartialEq,Clone, andDefault.
§Returns
Vec<T>- A new vector containing only the non-zero elements from the input collection.
§Examples
use lowdash::compact;
let numbers = vec![0, 1, 0, 2, 3, 0, 4];
let compacted = compact(&numbers);
assert_eq!(compacted, vec![1, 2, 3, 4]);use lowdash::compact;
#[derive(Debug, PartialEq, Clone, Default)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "".to_string(), age: 0 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "".to_string(), age: 0 },
Person { name: "Dave".to_string(), age: 40 },
];
let compacted = compact(&people);
assert_eq!(
compacted,
vec![
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Dave".to_string(), age: 40 },
]
);use lowdash::compact;
let floats = vec![0.0, 1.1, 0.0, 2.2, 3.3, 0.0, 4.4];
let compacted = compact(&floats);
assert_eq!(compacted, vec![1.1, 2.2, 3.3, 4.4]);