Skip to content

mapify

Convert an array to a map

113 bytes

Usage

The mapify function converts an array into a Map object, allowing you to specify how keys and values are derived from each array item.

Parameters

  1. array: The input array to be converted into a Map.
  2. getKey: A function that determines the key for each item in the array. It receives two arguments:
    • item: The current array item.
    • index: The index of the current item in the array.
  3. getValue (optional): A function that determines the value for each item in the array. If not provided, the original array item is used as the value. It also receives two arguments:
    • item: The current array item.
    • index: The index of the current item in the array.

Return Value

Returns a new Map object where keys and values are derived from the input array using the provided mapping functions.

Example

import * as _ from 'radashi'
const fish = [
{
name: 'Marlin',
weight: 105,
},
{
name: 'Bass',
weight: 8,
},
{
name: 'Trout',
weight: 13,
},
]
_.mapify(fish, f => f.name) // => Map(3) {'Marlin' => { name: 'Marlin', weight: 105 }, 'Bass' => { name: 'Bass', weight: 8 }, 'Trout' => { name: 'Trout', weight: 13 }}
_.mapify(
fish,
f => f.name,
f => f.weight,
) // => Map(3) { 'Marlin' => 105, 'Bass' => 8, 'Trout' => 13 }