Skip to content

Archive

Map

4 articles
JavaScript Updated 02 Sep 2025 2 min read

Group Data with JavaScript `Map.groupBy()`

Map.groupBy() groups iterable values into a Map. The callback determines the key for each group, and every map value is an array of matching elements. Basic Example const numbers = [1, 2, 3, 4, 5, 6]; const grouped = Map.groupBy(numbers, (number) => number % 2 === 0 ? 'even' : 'odd' ); console.log(grouped.get('even')); // [2, 4, 6] Group Objects const products = [ { name: 'Laptop', category: 'Electronics' }, { name: 'Shirt', category: 'Clothing' }, { name: 'Phone', category: 'Electronics' }, ]; const grouped = Map.groupBy(products, (product) => product.category); Arbitrary Map Keys The main advantage over Object.groupBy() is that map keys can be objects and other values without being converted to property keys:

Go Updated 02 Sep 2025 2 min read

Maps in Go: A Practical Guide with Examples

A Go map stores key-value pairs and gives you fast lookup by key. It is similar to a dictionary or hash map in other languages and is one of Go’s most useful built-in data structures. Creating a Map Using make: personAge := make(map[string]int) personAge["Alice"] = 30 personAge["Bob"] = 25 fmt.Println(personAge) Using a map literal:

Go Updated 02 Sep 2025 2 min read

How to Get a Slice of Map Keys in Go

Go maps store key-value pairs, but many tasks only need the keys—for example, to sort them, display them, compare sets, or feed them into another operation. Map iteration is intentionally unordered, so extracting keys into a slice is also the first step when you need a deterministic order. 1. Collect All Keys with range func getMapKeys(m map[string]int) []string { keys := make([]string, 0, len(m)) for k := range m { keys = append(keys, k) } return keys } func main() { myMap := map[string]int{ "apple": 1, "banana": 2, "cherry": 3, } keys := getMapKeys(myMap) fmt.Println("Keys:", keys) } Preallocating the slice with capacity len(m) avoids unnecessary growth while keys are appended.

Go Updated 02 Sep 2025 2 min read

How to Check Whether a Map Contains a Key in Go

Go has a built-in idiom for checking whether a map contains a key. A map lookup can return both the stored value and a boolean indicating whether the key is present. Check a Key myMap := map[string]int{ "apple": 1, "banana": 2, "cherry": 3, } key := "banana" value, exists := myMap[key] if exists { fmt.Printf("Key '%s' exists with value %d\n", key, value) } else { fmt.Printf("Key '%s' does not exist\n", key) } The boolean is important because a missing key returns the value type’s zero value. Without the boolean, you cannot distinguish a missing key from a present key whose stored value happens to be zero.