Skip to content
The Chat Archive
gpt-4.1-2025-04-14· OpenAI LMArena Human Preference 140K

Do the same but for map values instead of a slice func FilterValuesT any bool) []T {…

  1. User

    Do the same but for map values instead of a slice

    func FilterValues[T any](list []T, predicate func(T) bool) []T { result := make([]T, 0, len(list))

    for _, v := range list {
    	if predicate(v) {
    		result = append(result, v)
    	}
    }
    
    return result
    

    }

  2. Assistant

    Certainly! Here’s a generic Go function that filters the values of a map based on a predicate, returning a new map with only the key-value pairs where the value matches the predicate.

    func FilterMapValues[K comparable, V any](m map[K]V, predicate func(V) bool) map[K]V {
        result := make(map[K]V, len(m))
        for k, v := range m {
            if predicate(v) {
                result[k] = v
            }
        }
        return result
    }
    

    Usage example:

    m := map[string]int{"a": 1, "b": 2, "c": 3}
    filtered := FilterMapValues(m, func(v int) bool { return v%2 == 1 })
    // filtered is map[string]int{"a": 1, "c": 3}
    

    Let me know if you want a version that returns just the filtered values as a slice, or if you want to filter by key!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.