Junior — Middle
How can specific objects be selected from a collection based on given conditions?
sobes.tech AI
Answer from AI
Filtering is commonly used to select specific objects from a collection based on given conditions. Depending on the language and tools, this can be:
- Using loops with conditional statements
- Higher-order functions, such as
filterorselect - Database queries with conditions
Example in Go for a slice of structs:
type Item struct {
ID int
Name string
Price float64
}
func filterItems(items []Item, minPrice float64) []Item {
var result []Item
for _, item := range items {
if item.Price >= minPrice {
result = append(result, item)
}
}
return result
}
In QA Automation, tools and languages that support filtering are often used, for example, in Python:
items = [{'id':1, 'status':'active'}, {'id':2, 'status':'inactive'}]
active_items = [item for item in items if item['status'] == 'active']
Thus, selecting objects based on conditions involves applying filtering through loops or built-in functions, which allows obtaining a subset of the collection that meets the specified criteria.