Functional programming methods that work similarly to Array methods but maintain Collection context. These methods enable powerful data transformation and analysis workflows with full type safety.
Transform collection values while preserving keys or converting to arrays.
/**
* Maps each item to another value into an array
* @param fn - Function that produces an element of the new array, taking three arguments
* @param thisArg - Value to use as 'this' when executing the function
* @returns Array of transformed values
*/
map<NewValue>(fn: (value: Value, key: Key, collection: this) => NewValue): NewValue[];
map<This, NewValue>(fn: (this: This, value: Value, key: Key, collection: this) => NewValue, thisArg: This): NewValue[];
/**
* Maps each item to another value into a collection
* @param fn - Function that produces an element of the new collection, taking three arguments
* @param thisArg - Value to use as 'this' when executing the function
* @returns New collection with transformed values but same keys
*/
mapValues<NewValue>(fn: (value: Value, key: Key, collection: this) => NewValue): Collection<Key, NewValue>;
mapValues<This, NewValue>(fn: (this: This, value: Value, key: Key, collection: this) => NewValue, thisArg: This): Collection<Key, NewValue>;
/**
* Maps each item into a Collection, then joins the results into a single Collection
* @param fn - Function that produces a new Collection
* @param thisArg - Value to use as 'this' when executing the function
* @returns Flattened collection of all results
*/
flatMap<NewValue>(fn: (value: Value, key: Key, collection: this) => Collection<Key, NewValue>): Collection<Key, NewValue>;
flatMap<NewValue, This>(fn: (this: This, value: Value, key: Key, collection: this) => Collection<Key, NewValue>, thisArg: This): Collection<Key, NewValue>;Usage Examples:
import { Collection } from "@discordjs/collection";
const users = new Collection([
["alice", { name: "Alice", age: 25, tags: ["admin", "premium"] }],
["bob", { name: "Bob", age: 30, tags: ["user"] }],
["charlie", { name: "Charlie", age: 35, tags: ["moderator", "premium"] }]
]);
// Map to array - extract names
const names = users.map(user => user.name);
// Result: ["Alice", "Bob", "Charlie"]
// Map values to new collection - add computed property
const usersWithStatus = users.mapValues(user => ({
...user,
isAdult: user.age >= 18,
displayName: user.name.toUpperCase()
}));
// FlatMap - extract all tags
const tagCollections = users.mapValues(user =>
new Collection(user.tags.map((tag, i) => [i, tag]))
);
const allTags = users.flatMap(user =>
new Collection(user.tags.map((tag, i) => [`${user.name}-${i}`, tag]))
);Find and filter items based on predicates.
/**
* Identical to Array.filter(), but returns a Collection instead of an Array
* @param fn - The function to test with (should return a boolean)
* @param thisArg - Value to use as 'this' when executing the function
* @returns New collection with items that pass the test
*/
filter<NewKey extends Key>(fn: (value: Value, key: Key, collection: this) => key is NewKey): Collection<NewKey, Value>;
filter<NewValue extends Value>(fn: (value: Value, key: Key, collection: this) => value is NewValue): Collection<Key, NewValue>;
filter(fn: (value: Value, key: Key, collection: this) => unknown): Collection<Key, Value>;
filter<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): Collection<Key, Value>;
/**
* Searches for a single item where the given function returns a truthy value
* @param fn - The function to test with (should return a boolean)
* @param thisArg - Value to use as 'this' when executing the function
* @returns First matching value or undefined
*/
find<NewValue extends Value>(fn: (value: Value, key: Key, collection: this) => value is NewValue): NewValue | undefined;
find(fn: (value: Value, key: Key, collection: this) => unknown): Value | undefined;
find<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): Value | undefined;
/**
* Searches for the key of a single item where the given function returns a truthy value
* @param fn - The function to test with (should return a boolean)
* @param thisArg - Value to use as 'this' when executing the function
* @returns First matching key or undefined
*/
findKey<NewKey extends Key>(fn: (value: Value, key: Key, collection: this) => key is NewKey): NewKey | undefined;
findKey(fn: (value: Value, key: Key, collection: this) => unknown): Key | undefined;
findKey<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): Key | undefined;
/**
* Searches for a last item where the given function returns a truthy value
* @param fn - The function to test with (should return a boolean)
* @param thisArg - Value to use as 'this' when executing the function
* @returns Last matching value or undefined
*/
findLast<NewValue extends Value>(fn: (value: Value, key: Key, collection: this) => value is NewValue): NewValue | undefined;
findLast(fn: (value: Value, key: Key, collection: this) => unknown): Value | undefined;
findLast<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): Value | undefined;
/**
* Searches for the key of a last item where the given function returns a truthy value
* @param fn - The function to test with (should return a boolean)
* @param thisArg - Value to use as 'this' when executing the function
* @returns Last matching key or undefined
*/
findLastKey<NewKey extends Key>(fn: (value: Value, key: Key, collection: this) => key is NewKey): NewKey | undefined;
findLastKey(fn: (value: Value, key: Key, collection: this) => unknown): Key | undefined;
findLastKey<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): Key | undefined;Usage Examples:
const users = new Collection([
["alice", { name: "Alice", age: 25, role: "admin" }],
["bob", { name: "Bob", age: 17, role: "user" }],
["charlie", { name: "Charlie", age: 30, role: "moderator" }]
]);
// Filter adults
const adults = users.filter(user => user.age >= 18);
// Result: Collection with alice and charlie
// Find first admin
const firstAdmin = users.find(user => user.role === "admin");
// Result: { name: "Alice", age: 25, role: "admin" }
// Find key of first adult
const firstAdultKey = users.findKey(user => user.age >= 18);
// Result: "alice"
// Find last user with age > 20
const lastOlderUser = users.findLast(user => user.age > 20);
// Result: { name: "Charlie", age: 30, role: "moderator" }Split collections based on conditions.
/**
* Partitions the collection into two collections where the first collection
* contains the items that passed and the second contains the items that failed
* @param fn - Function used to test (should return a boolean)
* @param thisArg - Value to use as 'this' when executing the function
* @returns Tuple of [passed, failed] collections
*/
partition<NewKey extends Key>(fn: (value: Value, key: Key, collection: this) => key is NewKey): [Collection<NewKey, Value>, Collection<Exclude<Key, NewKey>, Value>];
partition<NewValue extends Value>(fn: (value: Value, key: Key, collection: this) => value is NewValue): [Collection<Key, NewValue>, Collection<Key, Exclude<Value, NewValue>>];
partition(fn: (value: Value, key: Key, collection: this) => unknown): [Collection<Key, Value>, Collection<Key, Value>];
partition<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): [Collection<Key, Value>, Collection<Key, Value>];Usage Example:
const users = new Collection([
["alice", { name: "Alice", age: 25, premium: true }],
["bob", { name: "Bob", age: 17, premium: false }],
["charlie", { name: "Charlie", age: 30, premium: true }]
]);
// Partition by premium status
const [premiumUsers, regularUsers] = users.partition(user => user.premium);
// premiumUsers: Collection with alice and charlie
// regularUsers: Collection with bobReduce collection to single values or test all/some items.
/**
* Applies a function to produce a single value
* @param fn - Function used to reduce, taking four arguments: accumulator, currentValue, currentKey, and collection
* @param initialValue - Starting value for the accumulator
* @returns Final accumulated value
*/
reduce(fn: (accumulator: Value, value: Value, key: Key, collection: this) => Value, initialValue?: Value): Value;
reduce<InitialValue>(fn: (accumulator: InitialValue, value: Value, key: Key, collection: this) => InitialValue, initialValue: InitialValue): InitialValue;
/**
* Applies a function to produce a single value, processing from right to left
* @param fn - Function used to reduce, taking four arguments: accumulator, value, key, and collection
* @param initialValue - Starting value for the accumulator
* @returns Final accumulated value
*/
reduceRight(fn: (accumulator: Value, value: Value, key: Key, collection: this) => Value, initialValue?: Value): Value;
reduceRight<InitialValue>(fn: (accumulator: InitialValue, value: Value, key: Key, collection: this) => InitialValue, initialValue: InitialValue): InitialValue;
/**
* Checks if there exists an item that passes a test
* @param fn - Function used to test (should return a boolean)
* @param thisArg - Value to use as 'this' when executing the function
* @returns true if any item passes the test
*/
some(fn: (value: Value, key: Key, collection: this) => unknown): boolean;
some<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): boolean;
/**
* Checks if all items pass a test
* @param fn - Function used to test (should return a boolean)
* @param thisArg - Value to use as 'this' when executing the function
* @returns true if all items pass the test
*/
every<NewKey extends Key>(fn: (value: Value, key: Key, collection: this) => key is NewKey): this is Collection<NewKey, Value>;
every<NewValue extends Value>(fn: (value: Value, key: Key, collection: this) => value is NewValue): this is Collection<Key, NewValue>;
every(fn: (value: Value, key: Key, collection: this) => unknown): boolean;
every<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): boolean;Usage Examples:
const scores = new Collection([
["alice", 95],
["bob", 87],
["charlie", 92]
]);
// Sum all scores
const totalScore = scores.reduce((sum, score) => sum + score, 0);
// Result: 274
// Calculate average
const average = scores.reduce((sum, score) => sum + score, 0) / scores.size;
// Result: 91.33
// Check if any score is above 90
const hasHighScore = scores.some(score => score > 90);
// Result: true
// Check if all scores are passing (>= 60)
const allPassing = scores.every(score => score >= 60);
// Result: trueMethods that modify the collection or iterate through items.
/**
* Removes items that satisfy the provided filter function
* @param fn - Function used to test (should return a boolean)
* @param thisArg - Value to use as 'this' when executing the function
* @returns The number of removed entries
*/
sweep(fn: (value: Value, key: Key, collection: this) => unknown): number;
sweep<This>(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): number;
/**
* Identical to Map.forEach(), but returns the collection instead of undefined
* @param fn - Function to execute for each element
* @param thisArg - Value to use as 'this' when executing the function
* @returns The collection itself for chaining
*/
each(fn: (value: Value, key: Key, collection: this) => void): this;
each<This>(fn: (this: This, value: Value, key: Key, collection: this) => void, thisArg: This): this;
/**
* Runs a function on the collection and returns the collection
* @param fn - Function to execute
* @param thisArg - Value to use as 'this' when executing the function
* @returns The collection itself for chaining
*/
tap(fn: (collection: this) => void): this;
tap<This>(fn: (this: This, collection: this) => void, thisArg: This): this;Usage Examples:
const users = new Collection([
["alice", { name: "Alice", active: true, lastLogin: Date.now() }],
["bob", { name: "Bob", active: false, lastLogin: Date.now() - 86400000 }],
["charlie", { name: "Charlie", active: true, lastLogin: Date.now() - 3600000 }]
]);
// Remove inactive users
const removedCount = users.sweep(user => !user.active);
// Result: 1, and bob is removed from the collection
// Chain operations with each
users
.each(user => console.log(`Processing ${user.name}`))
.filter(user => user.active)
.each(user => console.log(`Active user: ${user.name}`));
// Use tap for debugging
const result = users
.filter(user => user.active)
.tap(coll => console.log(`Found ${coll.size} active users`))
.map(user => user.name);