Collection

export declare class Collection<Key, Value> extends Map<Key, Value>
export declare class Collection<Key, Value> extends Map<Key, Value>
A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has an ID, for significantly improved performance and ease-of-use.

Extends

Map<Key, Value>
NameConstraintsOptionalDefaultDescription
KeyNoThe key type this collection holds
ValueNoThe value type this collection holds
at(index):Value | undefined
Identical to Array.at(). Returns the item at a given index, allowing for positive and negative integers. Negative integers count back from the last item in the collection.
NameTypeOptionalDescription
indexnumberNoThe index of the element to obtain
clone():Collection<Key, Value>
Creates an identical shallow copy of this collection.
Example
const newColl = someColl.clone();
const newColl = someColl.clone();
Static
combineEntries(entries, combine):Collection<Key, Value>
Creates a Collection from a list of entries.
Example
Collection.combineEntries([["a", 1], ["b", 2], ["a", 2]], (x, y) => x + y);
// returns Collection { "a" => 3, "b" => 2 }
Collection.combineEntries([["a", 1], ["b", 2], ["a", 2]], (x, y) => x + y);
// returns Collection { "a" => 3, "b" => 2 }
NameConstraintsOptionalDefaultDescription
KeyNoNone
ValueNoNone
NameTypeOptionalDescription
entriesIterable<[Key, Value]>NoThe list of entries
combine(firstValue: Value, secondValue: Value, key: Key) => ValueNoFunction to combine an existing entry with a new one
concat(...collections):Collection<Key, Value>
Combines this collection with others into a new collection. None of the source collections are modified.
Example
const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);
const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);
NameTypeOptionalDescription
...collectionsReadonlyCollection<Key, Value>[]NoCollections to merge
difference(other):Collection<Key, Value>
Returns a new collection containing the items where the key is present in this collection but not the other.
Example
const col1 = new Collection([['a', 1], ['b', 2]]);
const col2 = new Collection([['a', 1], ['c', 3]]);
console.log(col1.difference(col2));
// => Collection { 'b' => 2 }
console.log(col2.difference(col1));
// => Collection { 'c' => 3 }
const col1 = new Collection([['a', 1], ['b', 2]]);
const col2 = new Collection([['a', 1], ['c', 3]]);
console.log(col1.difference(col2));
// => Collection { 'b' => 2 }
console.log(col2.difference(col1));
// => Collection { 'c' => 3 }
NameTypeOptionalDescription
otherReadonlyCollection<Key, any>NoThe other Collection to filter against
each(fn):this
Identical to Map.forEach(), but returns the collection instead of undefined.
Example
collection
.each(user => console.log(user.username))
.filter(user => user.bot)
.each(user => console.log(user.username));
collection
.each(user => console.log(user.username))
.filter(user => user.bot)
.each(user => console.log(user.username));
NameTypeOptionalDescription
fn(value: Value, key: Key, collection: this) => voidNoFunction to execute for each element
ensure(key, defaultValueGenerator):Value
Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator.
Example
collection.ensure(guildId, () => defaultGuildConfig);
collection.ensure(guildId, () => defaultGuildConfig);
NameTypeOptionalDescription
keyKeyNoThe key to get if it exists, or set otherwise
defaultValueGenerator(key: Key, collection: this) => ValueNoA function that generates the default value
equals(collection):boolean
Checks if this collection shares identical items with another. This is different to checking for equality using equal-signs, because the collections may be different objects, but contain the same data.
Returns
Whether the collections have identical contents
NameTypeOptionalDescription
collectionReadonlyCollection<Key, Value>NoCollection to compare with
every(fn):this is Collection<NewKey, Value>
Checks if all items passes a test. Identical in behavior to Array.every().
Example
collection.every(user => !user.bot);
collection.every(user => !user.bot);
NameConstraintsOptionalDefaultDescription
NewKeyKeyNoNone
NameTypeOptionalDescription
fn(value: Value, key: Key, collection: this) => key is NewKeyNoFunction used to test (should return a boolean)
filter(fn):Collection<NewKey, Value>
Identical to Array.filter(), but returns a Collection instead of an Array.
Example
collection.filter(user => user.username === 'Bob');
collection.filter(user => user.username === 'Bob');
NameConstraintsOptionalDefaultDescription
NewKeyKeyNoNone
NameTypeOptionalDescription
fn(value: Value, key: Key, collection: this) => key is NewKeyNoThe function to test with (should return a boolean)
find(fn):NewValue | undefined
Searches for a single item where the given function returns a truthy value. This behaves like Array.find(). All collections used in Discord.js are mapped using their id property, and if you want to find by id you should use the get method. See MDN for details.
Example
collection.find(user => user.username === 'Bob');
collection.find(user => user.username === 'Bob');
NameConstraintsOptionalDefaultDescription
NewValueValueNoNone
NameTypeOptionalDescription
fn(value: Value, key: Key, collection: this) => value is NewValueNoThe function to test with (should return a boolean)
findKey(fn):NewKey | undefined
Searches for the key of a single item where the given function returns a truthy value. This behaves like Array.findIndex(), but returns the key rather than the positional index.
Example
collection.findKey(user => user.username === 'Bob');
collection.findKey(user => user.username === 'Bob');
NameConstraintsOptionalDefaultDescription
NewKeyKeyNoNone
NameTypeOptionalDescription
fn(value: Value, key: Key, collection: this) => key is NewKeyNoThe function to test with (should return a boolean)
findLast(fn):NewValue | undefined
Searches for a last item where the given function returns a truthy value. This behaves like Array.findLast().
NameConstraintsOptionalDefaultDescription
NewValueValueNoNone
NameTypeOptionalDescription
fn(value: Value, key: Key, collection: this) => value is NewValueNoThe function to test with (should return a boolean)
findLastKey(fn):NewKey | undefined
Searches for the key of a last item where the given function returns a truthy value. This behaves like Array.findLastIndex(), but returns the key rather than the positional index.
NameConstraintsOptionalDefaultDescription
NewKeyKeyNoNone
NameTypeOptionalDescription
fn(value: Value, key: Key, collection: this) => key is NewKeyNoThe function to test with (should return a boolean)
first():Value | undefined
Obtains the first value(s) in this collection.
Returns
A single value if no amount is provided or an array of values, starting from the end if amount is negative
firstKey():Key | undefined
Obtains the first key(s) in this collection.
Returns
A single key if no amount is provided or an array of keys, starting from the end if amount is negative
flatMap(fn):Collection<Key, NewValue>
Maps each item into a Collection, then joins the results into a single Collection. Identical in behavior to Array.flatMap().
Example
collection.flatMap(guild => guild.members.cache);
collection.flatMap(guild => guild.members.cache);
NameConstraintsOptionalDefaultDescription
NewValueNoNone
NameTypeOptionalDescription
fn(value: Value, key: Key, collection: this) => Collection<Key, NewValue>NoFunction that produces a new Collection
hasAll(...keys):boolean
Checks if all of the elements exist in the collection.
Returns
true if all of the elements exist, false if at least one does not exist.
NameTypeOptionalDescription
...keysKey[]NoThe keys of the elements to check for
hasAny(...keys):boolean
Checks if any of the elements exist in the collection.
Returns
true if any of the elements exist, false if none exist.
NameTypeOptionalDescription
...keysKey[]NoThe keys of the elements to check for
intersection(other):Collection<Key, Value>
The intersection method returns a new collection containing the items where the key is present in both collections.
Example
const col1 = new Collection([['a', 1], ['b', 2]]);
const col2 = new Collection([['a', 1], ['c', 3]]);
const intersection = col1.intersection(col2);
console.log(col1.intersection(col2));
// => Collection { 'a' => 1 }
const col1 = new Collection([['a', 1], ['b', 2]]);
const col2 = new Collection([['a', 1], ['c', 3]]);
const intersection = col1.intersection(col2);
console.log(col1.intersection(col2));
// => Collection { 'a' => 1 }
NameTypeOptionalDescription
otherReadonlyCollection<Key, any>NoThe other Collection to filter against
keyAt(index):Key | undefined
Identical to Array.at(). Returns the key at a given index, allowing for positive and negative integers. Negative integers count back from the last item in the collection.
NameTypeOptionalDescription
indexnumberNoThe index of the key to obtain
last():Value | undefined
Obtains the last value(s) in this collection.
Returns
A single value if no amount is provided or an array of values, starting from the start if amount is negative
lastKey():Key | undefined
Obtains the last key(s) in this collection.
Returns
A single key if no amount is provided or an array of keys, starting from the start if amount is negative
map(fn):NewValue[]
Maps each item to another value into an array. Identical in behavior to Array.map().
Example
collection.map(user => user.tag);
collection.map(user => user.tag);
NameConstraintsOptionalDefaultDescription
NewValueNoNone
NameTypeOptionalDescription
fn(value: Value, key: Key, collection: this) => NewValueNoFunction that produces an element of the new array, taking three arguments
mapValues(fn):Collection<Key, NewValue>
Maps each item to another value into a collection. Identical in behavior to Array.map().
Example
collection.mapValues(user => user.tag);
collection.mapValues(user => user.tag);
NameConstraintsOptionalDefaultDescription
NewValueNoNone
NameTypeOptionalDescription
fn(value: Value, key: Key, collection: this) => NewValueNoFunction that produces an element of the new collection, taking three arguments
merge(other, whenInSelf, whenInOther, whenInBoth):Collection<Key, ResultValue>
Merges two Collections together into a new Collection.
Example
// Sums up the entries in two collections.
coll.merge(
other,
x => ({ keep: true, value: x }),
y => ({ keep: true, value: y }),
(x, y) => ({ keep: true, value: x + y }),
);
// Sums up the entries in two collections.
coll.merge(
other,
x => ({ keep: true, value: x }),
y => ({ keep: true, value: y }),
(x, y) => ({ keep: true, value: x + y }),
);
Example
// Intersects two collections in a left-biased manner.
coll.merge(
other,
x => ({ keep: false }),
y => ({ keep: false }),
(x, _) => ({ keep: true, value: x }),
);
// Intersects two collections in a left-biased manner.
coll.merge(
other,
x => ({ keep: false }),
y => ({ keep: false }),
(x, _) => ({ keep: true, value: x }),
);
NameConstraintsOptionalDefaultDescription
OtherValueNoNone
ResultValueNoNone
NameTypeOptionalDescription
otherReadonlyCollection<Key, OtherValue>NoThe other Collection to merge with
whenInSelf(value: Value, key: Key) => Keep<ResultValue>NoFunction getting the result if the entry only exists in this Collection
whenInOther(valueOther: OtherValue, key: Key) => Keep<ResultValue>NoFunction getting the result if the entry only exists in the other Collection
whenInBoth(value: Value, valueOther: OtherValue, key: Key) => Keep<ResultValue>NoFunction getting the result if the entry exists in both Collections
partition(fn):[Collection<NewKey, Value>, Collection<Exclude<Key, NewKey>, Value>]
Partitions the collection into two collections where the first collection contains the items that passed and the second contains the items that failed.
Example
const [big, small] = collection.partition(guild => guild.memberCount > 250);
const [big, small] = collection.partition(guild => guild.memberCount > 250);
NameConstraintsOptionalDefaultDescription
NewKeyKeyNoNone
NameTypeOptionalDescription
fn(value: Value, key: Key, collection: this) => key is NewKeyNoFunction used to test (should return a boolean)
random():Value | undefined
Obtains unique random value(s) from this collection.
Returns
A single value if no amount is provided or an array of values
randomKey():Key | undefined
Obtains unique random key(s) from this collection.
Returns
A single key if no amount is provided or an array
reduce(fn, initialValue?):Value
Applies a function to produce a single value. Identical in behavior to Array.reduce().
Example
collection.reduce((acc, guild) => acc + guild.memberCount, 0);
collection.reduce((acc, guild) => acc + guild.memberCount, 0);
NameTypeOptionalDescription
fn(accumulator: Value, value: Value, key: Key, collection: this) => ValueNoFunction used to reduce, taking four arguments; accumulator, currentValue, currentKey, and collection
initialValueValueYesStarting value for the accumulator
reduceRight(fn, initialValue?):Value
Applies a function to produce a single value. Identical in behavior to Array.reduceRight().
NameTypeOptionalDescription
fn(accumulator: Value, value: Value, key: Key, collection: this) => ValueNoFunction used to reduce, taking four arguments; accumulator, value, key, and collection
initialValueValueYesStarting value for the accumulator
reverse():this
Identical to Array.reverse() but returns a Collection instead of an Array.
some(fn):boolean
Checks if there exists an item that passes a test. Identical in behavior to Array.some().
Example
collection.some(user => user.discriminator === '0000');
collection.some(user => user.discriminator === '0000');
NameTypeOptionalDescription
fn(value: Value, key: Key, collection: this) => unknownNoFunction used to test (should return a boolean)
sort(compareFunction?):this
The sort method sorts the items of a collection in place and returns it. If a comparison function is not provided, the function sorts by element values, using the same stringwise comparison algorithm as Array.sort().
Example
collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);
collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);
NameTypeOptionalDescription
compareFunctionComparator<Key, Value>YesSpecifies a function that defines the sort order. The return value of this function should be negative if a comes before b, positive if b comes before a, or zero if a and b are considered equal.
sweep(fn):number
Removes items that satisfy the provided filter function.
Returns
The number of removed entries
NameTypeOptionalDescription
fn(value: Value, key: Key, collection: this) => unknownNoFunction used to test (should return a boolean)
symmetricDifference(other):Collection<Key, OtherValue | Value>
Returns a new collection containing only the items where the keys are present in either collection, but not both.
Example
const col1 = new Collection([['a', 1], ['b', 2]]);
const col2 = new Collection([['a', 1], ['c', 3]]);
const symmetricDifference = col1.symmetricDifference(col2);
console.log(col1.symmetricDifference(col2));
// => Collection { 'b' => 2, 'c' => 3 }
const col1 = new Collection([['a', 1], ['b', 2]]);
const col2 = new Collection([['a', 1], ['c', 3]]);
const symmetricDifference = col1.symmetricDifference(col2);
console.log(col1.symmetricDifference(col2));
// => Collection { 'b' => 2, 'c' => 3 }
NameConstraintsOptionalDefaultDescription
OtherValueNoNone
NameTypeOptionalDescription
otherReadonlyCollection<Key, OtherValue>NoThe other Collection to filter against
tap(fn):this
Runs a function on the collection and returns the collection.
Example
collection
.tap(coll => console.log(coll.size))
.filter(user => user.bot)
.tap(coll => console.log(coll.size))
collection
.tap(coll => console.log(coll.size))
.filter(user => user.bot)
.tap(coll => console.log(coll.size))
NameTypeOptionalDescription
fn(collection: this) => voidNoFunction to execute
toJSON():[Key, Value][]
toReversed():Collection<Key, Value>
Identical to Array.toReversed() but returns a Collection instead of an Array.
toSorted(compareFunction?):Collection<Key, Value>
The toSorted method returns a shallow copy of the collection with the items sorted. If a comparison function is not provided, the function sorts by element values, using the same stringwise comparison algorithm as Array.sort().
Example
const sortedCollection = collection.toSorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);
const sortedCollection = collection.toSorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);
NameTypeOptionalDescription
compareFunctionComparator<Key, Value>YesSpecifies a function that defines the sort order. The return value of this function should be negative if a comes before b, positive if b comes before a, or zero if a and b are considered equal.
union(other):Collection<Key, OtherValue | Value>
Returns a new collection containing the items where the key is present in either of the collections.
Remarks
If the collections have any items with the same key, the value from the first collection will be used.
Example
const col1 = new Collection([['a', 1], ['b', 2]]);
const col2 = new Collection([['a', 1], ['b', 3], ['c', 3]]);
const union = col1.union(col2);
console.log(union);
// => Collection { 'a' => 1, 'b' => 2, 'c' => 3 }
const col1 = new Collection([['a', 1], ['b', 2]]);
const col2 = new Collection([['a', 1], ['b', 3], ['c', 3]]);
const union = col1.union(col2);
console.log(union);
// => Collection { 'a' => 1, 'b' => 2, 'c' => 3 }
NameConstraintsOptionalDefaultDescription
OtherValueNoNone
NameTypeOptionalDescription
otherReadonlyCollection<Key, OtherValue>NoThe other Collection to filter against