keyBy (for Sets) ​
Maps each element of a Set based on a provided key-generating function.
typescript
const result = keyBy(set, getKeyFromValue);INFO
This function is available exclusively from es-toolkit/set to avoid potential conflicts with similar functions for other collection types.
Usage ​
keyBy(set, getKeyFromValue) ​
Use keyBy when you want to convert a Set into a Map by generating keys from the values. Provide a function that generates a key from each value, and it returns a new Map where the keys are generated by the key function and the values are the corresponding values from the original set. If multiple elements produce the same key, the last value encountered will be used.
typescript
import { keyBy } from 'es-toolkit/set';
const set = new Set([
{ type: 'fruit', name: 'apple' },
{ type: 'fruit', name: 'banana' },
{ type: 'vegetable', name: 'carrot' },
]);
const result = keyBy(set, item => item.type);
// Result:
// Map(2) {
// 'fruit' => { type: 'fruit', name: 'banana' },
// 'vegetable' => { type: 'vegetable', name: 'carrot' }
// }
// Note: 'banana' is kept because it was the last 'fruit' encounteredYou can create indexes based on various criteria.
typescript
import { keyBy } from 'es-toolkit/set';
// Index by ID
const users = new Set([
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' },
]);
const byId = keyBy(users, user => user.id);
// Result: Map(3) { 1 => {...}, 2 => {...}, 3 => {...} }
// Index by name
const byName = keyBy(users, user => user.name);
// Result: Map with keys 'Alice', 'Bob', 'Charlie'
// Index by derived value
const numbers = new Set([1, 2, 3, 4, 5]);
const byParity = keyBy(numbers, num => (num % 2 === 0 ? 'even' : 'odd'));
// Result: Map(2) {
// 'odd' => 5,
// 'even' => 4
// }
// Note: Last even (4) and last odd (5) values are keptParameters ​
set(Set<T>): The set of elements to be mapped.getKeyFromValue((value: T, value2: T, set: Set<T>) => K): A function that generates a key from a value.
Returns ​
(Map<K, T>): A Map where the generated keys are mapped to each element's value.

