# Collection

class

Collections are ordered sets of objects. Items in the collection can be retrieved by their indexes in the collection (like in an array) or by their ids.

If an object without an `id` property is being added to the collection, the `id` property will be generated automatically. Note that the automatically generated id is unique only within this single collection instance.

By default an item in the collection is identified by its `id` property. The name of the identifier can be configured through the constructor of the collection.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L29)

<a id="type-parameters">

## Type parameters

### `T: extends Record<string, any>`

The type of the collection element.

<a id="properties">

## Properties

<a id="member-first">

### `first: T | null` _(readonly)_

Returns the first item from the collection or null when collection is empty.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L167)

<a id="member-last">

### `last: T | null` _(readonly)_

Returns the last item from the collection or null when collection is empty.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L174)

<a id="member-length">

### `length: number` _(readonly)_

The number of items available in the collection.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L160)

<a id="member-_bindToCollection">

### `_bindToCollection?: Collection<any> | null` _(private)_

A collection instance this collection is bound to as a result of calling [`bindTo`](#function-bindTo) method.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L49)

<a id="member-_bindToExternalToInternalMap">

### `_bindToExternalToInternalMap: WeakMap<any, T>` _(private)_

A helper mapping external items of a bound collection ([`bindTo`](#function-bindTo)) and actual items of this collection. It provides information necessary to properly remove items bound to another collection.

See [`_bindToInternalToExternalMap`](#member-_bindToInternalToExternalMap).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L58)

<a id="member-_bindToInternalToExternalMap">

### `_bindToInternalToExternalMap: WeakMap<T, any>` _(private)_

A helper mapping items of this collection to external items of a bound collection ([`bindTo`](#function-bindTo)). It provides information necessary to manage the bindings, e.g. to avoid loops in two–way bindings.

See [`_bindToExternalToInternalMap`](#member-_bindToExternalToInternalMap).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L67)

<a id="member-_idProperty">

### `_idProperty: string` _(private)_

The name of the property which is considered to identify an item.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L43)

<a id="member-_itemMap">

### `_itemMap: Map<string, T>` _(private)_

The internal map of items in the collection.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L38)

<a id="member-_items">

### `_items: Array<T>` _(private)_

The internal list of items in the collection.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L33)

<a id="member-_skippedIndexesFromExternal">

### `_skippedIndexesFromExternal: Array<number>` _(private)_

Stores indexes of skipped items from bound external collection.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L72)

<a id="methods">

## Methods

<a id="function-constructor:INITIAL_ITEMS">

### `constructor( initialItems, options? = { options.idProperty? } )`

Creates a new Collection instance with specified initial items.

```typescript
const collection = new Collection<{ id: string }>( [ { id: 'John' }, { id: 'Mike' } ] );

console.log( collection.get( 0 ) ); // -> { id: 'John' }
console.log( collection.get( 1 ) ); // -> { id: 'Mike' }
console.log( collection.get( 'Mike' ) ); // -> { id: 'Mike' }
```

You can always pass a configuration object as the last argument of the constructor:

```typescript
const nonEmptyCollection = new Collection<{ name: string }>( [ { name: 'John' } ], { idProperty: 'name' } );
nonEmptyCollection.add( { name: 'George' } );
console.log( collection.get( 'George' ) ); // -> { name: 'George' }
console.log( collection.get( 'John' ) ); // -> { name: 'John' }
```

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L127)

#### Type parameters

* `T: extends Record<string, any>`

  The type of the collection element.

#### Parameters

* `initialItems: Iterable<T>`

  The initial items of the collection.

* `options?: object`

  The options object.

  Properties

  * `options.idProperty?: string`

    The name of the property which is used to identify an item. Items that do not have such a property will be assigned one when added to the collection.

<a id="function-constructor:NO_ITEMS">

### `constructor( options? = { options.idProperty? } )`

Creates a new Collection instance.

You can pass a configuration object as the argument of the constructor:

```typescript
const emptyCollection = new Collection<{ name: string }>( { idProperty: 'name' } );
emptyCollection.add( { name: 'John' } );
console.log( collection.get( 'John' ) ); // -> { name: 'John' }
```

The collection is empty by default. You can add new items using the [`add`](#function-add) method:

```typescript
const collection = new Collection<{ id: string }>();

collection.add( { id: 'John' } );
console.log( collection.get( 0 ) ); // -> { id: 'John' }
```

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L99)

#### Type parameters

* `T: extends Record<string, any>`

  The type of the collection element.

#### Parameters

* `options?: object`

  The options object.

  Properties

  * `options.idProperty?: string`

    The name of the property which is used to identify an item. Items that do not have such a property will be assigned one when added to the collection.

<a id="function-Symbol.iterator">

### `Symbol.iterator() → Iterator<T>`

Iterable interface.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L762)

#### Returns

* `Iterator<T>`

<a id="function-add">

### `add( item, index? ) → this`

Adds an item into the collection.

If the item does not have an id, then it will be automatically generated and set on the item.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L189)

#### Parameters

* `item: T`

* `index?: number`

  The position of the item in the collection. The item is pushed to the collection when `index` not specified.

#### Returns

* `this`

#### Fires

* [add](#event-add)
* [change](#event-change)

<a id="function-addMany">

### `addMany( items, index? ) → this`

Adds multiple items into the collection.

Any item not containing an id will get an automatically generated one.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L203)

#### Parameters

* `items: Iterable<T>`

* `index?: number`

  The position of the insertion. Items will be appended if no `index` is specified.

#### Returns

* `this`

#### Fires

* [add](#event-add)
* [change](#event-change)

<a id="function-bindTo">

### `bindTo( externalCollection ) → CollectionBindToChain<S, T>`

Binds and synchronizes the collection with another one.

The binding can be a simple factory:

```typescript
class FactoryClass {
	public label: string;

	constructor( data: { label: string } ) {
		this.label = data.label;
	}
}

const source = new Collection<{ label: string }>( { idProperty: 'label' } );
const target = new Collection<FactoryClass>();

target.bindTo( source ).as( FactoryClass );

source.add( { label: 'foo' } );
source.add( { label: 'bar' } );

console.log( target.length ); // 2
console.log( target.get( 1 ).label ); // 'bar'

source.remove( 0 );
console.log( target.length ); // 1
console.log( target.get( 0 ).label ); // 'bar'
```

or the factory driven by a custom callback:

```typescript
class FooClass {
	public label: string;

	constructor( data: { label: string } ) {
		this.label = data.label;
	}
}

class BarClass {
	public label: string;

	constructor( data: { label: string } ) {
		this.label = data.label;
	}
}

const source = new Collection<{ label: string }>( { idProperty: 'label' } );
const target = new Collection<FooClass | BarClass>();

target.bindTo( source ).using( ( item ) => {
	if ( item.label == 'foo' ) {
		return new FooClass( item );
	} else {
		return new BarClass( item );
	}
} );

source.add( { label: 'foo' } );
source.add( { label: 'bar' } );

console.log( target.length ); // 2
console.log( target.get( 0 ) instanceof FooClass ); // true
console.log( target.get( 1 ) instanceof BarClass ); // true
```

or the factory out of property name:

```typescript
const source = new Collection<{ nested: { value: string } }>();
const target = new Collection<{ value: string }>();

target.bindTo( source ).using( 'nested' );

source.add( { nested: { value: 'foo' } } );
source.add( { nested: { value: 'bar' } } );

console.log( target.length ); // 2
console.log( target.get( 0 ).value ); // 'foo'
console.log( target.get( 1 ).value ); // 'bar'
```

It's possible to skip specified items by returning null value:

```typescript
const source = new Collection<{ hidden: boolean }>();
const target = new Collection<{ hidden: boolean }>();

target.bindTo( source ).using( item => {
	if ( item.hidden ) {
		return null;
	}

	return item;
} );

source.add( { hidden: true } );
source.add( { hidden: false } );

console.log( source.length ); // 2
console.log( target.length ); // 1
```

**Note**: [`clear`](#function-clear) can be used to break the binding.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L512)

#### Type parameters

* `S: extends Record<string, any>`

  The type of `externalCollection` element.

#### Parameters

* `externalCollection: Collection<S>`

  A collection to be bound.

#### Returns

* `CollectionBindToChain<S, T>`

  The binding chain object.

<a id="function-clear">

### `clear() → void`

Removes all items from the collection and destroys the binding created using [`bindTo`](#function-bindTo).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L382)

#### Returns

* `void`

#### Fires

* [remove](#event-remove)
* [change](#event-change)

<a id="function-delegate">

### `delegate( events ) → EmitterMixinDelegateChain` _(inherited)_

Delegates selected events to another [`Emitter`](module_utils_emittermixin-Emitter.md). For instance:

```typescript
emitterA.delegate( 'eventX' ).to( emitterB );
emitterA.delegate( 'eventX', 'eventY' ).to( emitterC );
```

then `eventX` is delegated (fired by) `emitterB` and `emitterC` along with `data`:

```typescript
emitterA.fire( 'eventX', data );
```

and `eventY` is delegated (fired by) `emitterC` along with `data`:

```typescript
emitterA.fire( 'eventY', data );
```

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L539)

#### Parameters

* `events: Array<string>`

  Event names that will be delegated to another emitter.

#### Returns

* `EmitterMixinDelegateChain`

<a id="function-filter">

### `filter( callback, ctx? ) → Array<T>`

Returns an array with items for which the `callback` returned a true value.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L368)

#### Parameters

* `callback: ( item: T, index: number ) => boolean`

* `ctx?: any`

  Context in which the `callback` will be called.

#### Returns

* `Array<T>`

  The array with matching items.

<a id="function-find">

### `find( callback, ctx? ) → T | undefined`

Finds the first item in the collection for which the `callback` returns a true value.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L354)

#### Parameters

* `callback: ( item: T, index: number ) => boolean`

* `ctx?: any`

  Context in which the `callback` will be called.

#### Returns

* `T | undefined`

  The item for which `callback` returned a true value.

<a id="function-fire">

### `fire( eventOrInfo, args ) → GetEventInfo<TEvent>[ 'return' ]` _(inherited)_

Fires an event, executing all callbacks registered for it.

The first parameter passed to callbacks is an [`EventInfo`](module_utils_eventinfo-EventInfo.md) object, followed by the optional `args` provided in the `fire()` method call.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L512)

#### Type parameters

* `TEvent: extends BaseEvent`

  The type describing the event. See [`BaseEvent`](module_utils_emittermixin-BaseEvent.md).

#### Parameters

* `eventOrInfo: GetNameOrEventInfo<TEvent>`

  The name of the event or `EventInfo` object if event is delegated.

* `args: TEvent[ 'args' ]`

  Additional arguments to be passed to the callbacks.

#### Returns

* `GetEventInfo<TEvent>[ 'return' ]`

  By default the method returns `undefined`. However, the return value can be changed by listeners through modification of the [`evt.return`](module_utils_eventinfo-EventInfo.md#member-return)'s property (the event info is the first param of every callback).

<a id="function-forEach">

### `forEach( callback, ctx? ) → void`

Performs the specified action for each item in the collection.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L340)

#### Parameters

* `callback: ( item: T, index: number ) => unknown`

* `ctx?: any`

  Context in which the `callback` will be called.

#### Returns

* `void`

<a id="function-get">

### `get( idOrIndex ) → T | null`

Gets an item by its ID or index.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L245)

#### Parameters

* `idOrIndex: string | number`

  The item ID or index in the collection.

#### Returns

* `T | null`

  The requested item or `null` if such item does not exist.

<a id="function-getIndex">

### `getIndex( itemOrId ) → number`

Gets an index of an item in the collection. When an item is not defined in the collection, the index will equal -1.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L288)

#### Parameters

* `itemOrId: string | T`

  The item or its ID in the collection.

#### Returns

* `number`

  The index of a given item.

<a id="function-has">

### `has( itemOrId ) → boolean`

Returns a Boolean indicating whether the collection contains an item.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L270)

#### Parameters

* `itemOrId: string | T`

  The item or its ID in the collection.

#### Returns

* `boolean`

  `true` if the collection contains the item, `false` otherwise.

<a id="function-listenTo:BASE_EMITTER">

### `listenTo( emitter, event, callback, options? ) → void` _(inherited)_

Registers a callback function to be executed when an event is fired in a specific (emitter) object.

Events can be grouped in namespaces using `:`. When namespaced event is fired, it additionally fires all callbacks for that namespace.

```typescript
// myEmitter.on( ... ) is a shorthand for myEmitter.listenTo( myEmitter, ... ).
myEmitter.on( 'myGroup', genericCallback );
myEmitter.on( 'myGroup:myEvent', specificCallback );

// genericCallback is fired.
myEmitter.fire( 'myGroup' );
// both genericCallback and specificCallback are fired.
myEmitter.fire( 'myGroup:myEvent' );
// genericCallback is fired even though there are no callbacks for "foo".
myEmitter.fire( 'myGroup:foo' );
```

An event callback can [stop the event](module_utils_eventinfo-EventInfo.md#member-stop) and set the [return value](module_utils_eventinfo-EventInfo.md#member-return) of the [`fire`](#function-fire) method.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L475)

#### Type parameters

* `TEvent: extends BaseEvent`

  The type describing the event. See [`BaseEvent`](module_utils_emittermixin-BaseEvent.md).

#### Parameters

* `emitter: Emitter`

  The object that fires the event.

* `event: TEvent[ 'name' ]`

  The name of the event.

* `callback: GetCallback<TEvent>`

  The function to be called on event.

* `options?: GetCallbackOptions<TEvent>`

  Additional options.

#### Returns

* `void`

<a id="function-map">

### `map( callback, ctx? ) → Array<U>`

Executes the callback for each item in the collection and composes an array or values returned by this callback.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L328)

#### Type parameters

* `U`

  The result type of the callback.

#### Parameters

* `callback: ( item: T, index: number ) => U`

* `ctx?: any`

  Context in which the `callback` will be called.

#### Returns

* `Array<U>`

  The result of mapping.

<a id="function-off">

### `off( event, callback ) → void` _(inherited)_

Stops executing the callback on the given event. Shorthand for [`this.stopListening( this, event, callback )`](#function-stopListening:BASE_STOP).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L444)

#### Parameters

* `event: string`

  The name of the event.

* `callback: Function`

  The function to stop being called.

#### Returns

* `void`

<a id="function-on">

### `on( event, callback, options? ) → void` _(inherited)_

Registers a callback function to be executed when an event is fired.

Shorthand for [`this.listenTo( this, event, callback, options )`](#function-listenTo:BASE_EMITTER) (it makes the emitter listen on itself).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L416)

#### Type parameters

* `TEvent: extends BaseEvent`

  The type descibing the event. See [`BaseEvent`](module_utils_emittermixin-BaseEvent.md).

#### Parameters

* `event: TEvent[ 'name' ]`

  The name of the event.

* `callback: GetCallback<TEvent>`

  The function to be called on event.

* `options?: GetCallbackOptions<TEvent>`

  Additional options.

#### Returns

* `void`

<a id="function-once">

### `once( event, callback, options? ) → void` _(inherited)_

Registers a callback function to be executed on the next time the event is fired only. This is similar to calling [`on`](#function-on) followed by [`off`](#function-off) in the callback.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L431)

#### Type parameters

* `TEvent: extends BaseEvent`

  The type descibing the event. See [`BaseEvent`](module_utils_emittermixin-BaseEvent.md).

#### Parameters

* `event: TEvent[ 'name' ]`

  The name of the event.

* `callback: GetCallback<TEvent>`

  The function to be called on event.

* `options?: GetCallbackOptions<TEvent>`

  Additional options.

#### Returns

* `void`

<a id="function-remove">

### `remove( subject ) → T`

Removes an item from the collection.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L308)

#### Parameters

* `subject: string | number | T`

  The item to remove, its ID or index in the collection.

#### Returns

* `T`

  The removed item.

#### Fires

* [remove](#event-remove)
* [change](#event-change)

<a id="function-stopDelegating">

### `stopDelegating( event?, emitter? ) → void` _(inherited)_

Stops delegating events. It can be used at different levels:

* To stop delegating all events.
* To stop delegating a specific event to all emitters.
* To stop delegating a specific event to a specific emitter.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L552)

#### Parameters

* `event?: string`

  The name of the event to stop delegating. If omitted, stops it all delegations.

* `emitter?: Emitter`

  (requires `event`) The object to stop delegating a particular event to. If omitted, stops delegation of `event` to all emitters.

#### Returns

* `void`

<a id="function-stopListening:BASE_STOP">

### `stopListening( emitter?, event?, callback? ) → void` _(inherited)_

Stops listening for events. It can be used at different levels:

* To stop listening to a specific callback.
* To stop listening to a specific event.
* To stop listening to all events fired by a specific object.
* To stop listening to all events fired by all objects.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L497)

#### Parameters

* `emitter?: Emitter`

  The object to stop listening to. If omitted, stops it for all objects.

* `event?: string`

  (Requires the `emitter`) The name of the event to stop listening to. If omitted, stops it for all events from `emitter`.

* `callback?: Function`

  (Requires the `event`) The function to be removed from the call list for the given `event`.

#### Returns

* `void`

<a id="function-_getItemIdBeforeAdding">

### `_getItemIdBeforeAdding( item ) → string` _(private)_

Returns an unique id property for a given `item`.

The method will generate new id and assign it to the `item` if it doesn't have any.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L670)

#### Parameters

* `item: any`

  Item to be added.

#### Returns

* `string`

<a id="function-_remove">

### `_remove( subject ) → [ item: T, index: number ]` _(private)_

Core [`remove`](#function-remove) method implementation shared in other functions.

In contrast this method **does not** fire the [event-change](#event-change) event.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L710)

#### Parameters

* `subject: string | number | T`

  The item to remove, its id or index in the collection.

#### Returns

* `[ item: T, index: number ]`

  Returns an array with the removed item and its index.

#### Fires

* [remove](#event-remove)

<a id="function-_setUpBindToBinding">

### `_setUpBindToBinding( factory ) → void` _(private)_

Finalizes and activates a binding initiated by [`bindTo`](#function-bindTo).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L546)

#### Type parameters

* `S`

#### Parameters

* `factory: ( item: S ) => ( T | null )`

  A function which produces collection items.

#### Returns

* `void`

<a id="events">

## Events

<a id="event-add">

### `add( eventInfo, item, index )`

Fired when an item is added to the collection.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L774)

#### Parameters

* `eventInfo: EventInfo`

  An object containing information about the fired event.

* `item: T`

  The added item.

* `index: number`

  An index where the addition occurred.

<a id="event-change">

### `change( eventInfo, data )`

Fired when the collection was changed due to adding or removing items.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L785)

#### Parameters

* `eventInfo: EventInfo`

  An object containing information about the fired event.

* `data: CollectionChangeEventData<T>`

  Changed items.

<a id="event-remove">

### `remove( eventInfo, item, index )`

Fired when an item is removed from the collection.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/collection.ts#L818)

#### Parameters

* `eventInfo: EventInfo`

  An object containing information about the fired event.

* `item: T`

  The removed item.

* `index: number`

  Index from which item was removed.

---

Full index of the CKEditor 5 API reference: [llms.txt](llms.txt)
