require(["esri/core/Collection"], function(Collection) { /* code goes here */ });
Class: esri/core/Collection
Inheritance: Collection Accessor
Since: ArcGIS API for JavaScript 4.0

Collection is a generic object that stores an array of items of the same type. It provides useful utility methods for working with items in the Collection, including filter(), find(), and reduce().

A Collection can be of any type. For example, GraphicsLayer.graphics is a collection of graphics that are stored in the GraphicsLayer. You can use the methods found in the Collection class to add, remove, re-order, or manipulate graphics in a GraphicsLayer.

Another example of a Collection is Map.layers, which is a Collection of operational layers included in the Map.

// Removes a layer from the map using Collection.remove();
map.layers.remove(layer);

The change event fires each time an item is added, moved, or removed from the Collection. Since properties of type Collection cannot be watched, the change event should be used to notify the developer/user of changes made to the collection.

See also:

Constructors

new Collection(properties)

Parameter:
properties Object
optional

See the properties for a list of all the properties that may be passed into the constructor.

Property Overview

Any properties can be set, retrieved or listened to. See the Working with Properties topic.
NameTypeSummary
String

The name of the class.

more details
more details
Number

The number of items in the Collection.

more details
more details

Property Details

declaredClassStringreadonly

The name of the class. The declared class name is formatted as esri.folder.className.

lengthNumber

The number of items in the Collection.

Method Overview

NameReturn TypeSummary

Adds a single item to the collection.

more details
more details

Adds multiple items to the collection.

more details
more details
Collection

Creates a deep clone of the Collection.

more details
more details
Collection

Creates a new Collection containing the items in the original Collection joined with the items in the input array or Collection.

more details
more details
Boolean

Determines whether all items in the Collection pass a test defined by callback.

more details
more details
Collection

Filters the Collection's items based on a test defined by the callback function.

more details
more details
*

Returns an item in the Collection if that item passes a test as defined in the callback function.

more details
more details
Number

Returns the index of an item in the Collection if that item passes a test as defined in the callback function.

more details
more details
Collection

Flattens a hierarchical Collection containing at least one child collection.

more details
more details

Executes the input function for each item in the Collection.

more details
more details
*

Returns the item at the specified index.

more details
more details
Boolean

Indicates whether there is an event listener on the instance that matches the provided event name.

more details
more details
Boolean

Tests if an item is present in the new Collection.

more details
more details
Number

Returns the index of an element in the collection.

more details
more details
Boolean

Determines whether the passed value is a Collection.

more details
more details
String

Creates a string representation of the items in the Collection.

more details
more details
Number

Returns the last index of an element in the collection.

more details
more details
Collection

Passes each Collection item into the callback function and returns a new array of the returned values.

more details
more details
Object

Creates a subclass of Collection containing a typed object.

more details
more details
Object

Registers an event handler on the instance.

more details
more details
*

Removes the last item from the collection and returns it.

more details
more details
Number

Adds an item(s) to the end of the collection.

more details
more details
*

Reduces all items in the collection (from left to right) into a single variable using callback.

more details
more details
*

Reduces all items in the collection (from right to left) into a single variable using callback.

more details
more details

Removes an item from the collection.

more details
more details

Removes all items from the collection.

more details
more details
*

Removes an item from the collection at a specified index.

more details
more details
*

Removes each item in the input array.

more details
more details
*

Moves an item in the Collection to a specified index.

more details
more details
Collection

Reverses the collection in place.

more details
more details
*

Removes the first item from the collection (at index 0), and returns it.

more details
more details
Collection

Creates a new Collection comprised of a portion of the original Collection.

more details
more details
Boolean

Determines whether an item in the Collection passes a test defined by callback.

more details
more details

Sorts the Collection in place.

more details
more details
*[]

Removes existing items and/or adds new items to the collection.

more details
more details
*[]

Returns a new array object containing the Collection's items.

more details
more details
Number

Adds one or more items to the beginning of the collection.

more details
more details

Method Details

add(item, index)

Adds a single item to the collection. The change event is fired after an item is added to the Collection.

Parameters:
item *

The item to add.

index Number
optional

Zero-based index of where in the collection to add the item. If not specified, the items will be added at the end.

Example:
var gpc = new Graphic();  // Creates a new graphic
var layer = new GraphicsLayer(); // Creates a new graphics layer
layer.graphics.add(gpc);  // Adds graphic to layer's graphics collection

addMany(items, index)

Adds multiple items to the collection. The change event is fired after items are added to the Collection.

Parameters:
items *[] | Collection

An array or collection of items to add.

index Number
optional

Zero-based index of where in the collection to add the items. If not specified, the items will be added at the end.

Example:
// Creates two new graphics
var gpc1 = new Graphic();
var gpc2 = new Graphic();

var layer = new GraphicsLayer(); // Creates a new graphics layer

// Adds both graphics to layer's graphics collection
layer.graphics.addMany([gpc1, gpc2]);

clone(){Collection}

Creates a deep clone of the Collection. To create a shallow clone of the collection, use slice().

Returns:
TypeDescription
CollectionA clone of the Collection that invoked this method.
See also:
Example:
// slides is a clone of the scene slides
var slides = scene.presentation.slides.clone();

concat(value){Collection}

Creates a new Collection containing the items in the original Collection joined with the items in the input array or Collection.

Parameter:
value *[] | Collection

The array or Collection to append to the existing Collection.

Returns:
TypeDescription
CollectionA new of the Collection.
See also:
Example:
// creating a collection of all the basemap's layers.
var basemap = map.basemap;
var basemapLayers = basemap.baseLayers.concat(basemap.referenceLayers);

every(callback){Boolean}

Determines whether all items in the Collection pass a test defined by callback. Each item in the Collection is passed into the callback until one returns a value of false.

Parameter:

The function to call for each item in the Collection.

Returns:
TypeDescription
BooleanReturns true if every call to the callback function returned true. Returns false if at least one call to the callback returned false.
See also:
Example:
var meetsStandardSize = graphicsLayer.graphics.every(function(item, i){
  // Tests each geometry's area to see if it is greater than 1,000 acres
  return calculateArea(item.geometry) > 1000;
});

filter(callback){Collection}

Filters the Collection's items based on a test defined by the callback function. Each item is passed into the callback function, which returns true if the item passes the test and false if it does not.

Parameter:

The function that defines a test for determining whether to return the item in a new Collection.

Returns:
TypeDescription
CollectionReturns a new Collection containing the items that passed the filter test.
See also:
Example:
// filteredLayers is a Collection of all the non-visible layers in the map
var filteredLayers = map.layers.filter(function(lyr){
  return !lyr.visible;
});

find(callback){*}

Returns an item in the Collection if that item passes a test as defined in the callback function. Each item is passed into the callback function, which returns true if the item passes the test and false if it does not.

Parameter:

The testing function that will assess each item in the Collection. Returns true if an item passes the test and false if it fails.

Returns:
TypeDescription
*The first item in the Collection that satsifies the test function.
See also:
Example:
// If the id of a map layer is already known, get the layer that matches the id
var myLayer = map.layers.find(function(lyr){
  return lyr.id === "speciesLyr01";
});
// myLayer references the layer in map with ID "speciesLyr01"

findIndex(callback){Number}

Returns the index of an item in the Collection if that item passes a test as defined in the callback function. Each item is passed into the callback function, which returns true if the item passes the test and false if it does not.

Parameter:

The testing function that will assess each item in the Collection. Returns true if an item passes the test and false if it fails.

Returns:
TypeDescription
NumberReturns the index of the Collection item that satsifies the test function. If an item fails the test, -1 is returned.
See also:
Example:
// gpcIndex is assigned the index of the first graphic whose name
// property is 'Redlands'. This result can be used in getItemAt()
var gpcIndex = graphicsLyr.graphics.findIndex(function(item){
  return item.attributes.name === "Redlands";
});

flatten(callback){Collection}

Flattens a hierarchical Collection containing at least one child collection. Each item in the collection is passed into the callback function, which should check for child collections specified by the developer. A flat collection of all items (parent and children) is returned.

This is useful for scenarios where the user would like to search all the layers in a map, including a GroupLayer's layers and a MapImageLayer's sublayers. The callback should return the sub-collection of the item. If multiple levels of collections exist in the hierarchy, then this method recursively executes for all sub-collections.

Parameter:
callback ItemCallback

A function that will assess each item in the Collection.

Returns:
TypeDescription
CollectionReturns a flat collection of all items in the original collection and their children.
Example:
// create a MapImageLayer with several sublayers and add to a map
// containing another GraphicsLayer
var layer = new MapImageLayer({ sublayers: [ ... ] });
var map = new Map({
  layers: [ layer, new GraphicsLayer() ]
});

// A flat collection of all layers and sublayers
// (if layer is a MapImageLayer) in the map.
// This collection may be searched or used for other purposes
var allLayersAndSublayers = map.layers.flatten(function(item){
  return item.layers || item.sublayers;
});

forEach(callback)

Executes the input function for each item in the Collection.

Parameter:
callback ItemCallback

The function to call for each item in the Collection.

See also:
Example:
graphicsLayer.graphics.forEach(function(item, i){
  // Do something here to each graphic like calculate area of its geometry
  calculateArea(item.geometry);
});

getItemAt(index){*}

Returns the item at the specified index.

Parameter:
index Number

Zero-based index of the item in the Collection to retrieve.

Returns:
TypeDescription
*The item in the Collection stored at the specifed index.
Example:
// Assigns the base layer at index 0 to baseLayer
var baseLayer = map.basemap.baseLayers.getItemAt(0);

hasEventListener(type){Boolean}

Indicates whether there is an event listener on the instance that matches the provided event name.

Parameter:
type String

The name of the event.

Returns:
TypeDescription
BooleanReturns true if the class supports the input event.

includes(searchElement){Boolean}

Tests if an item is present in the new Collection.

Parameter:
searchElement *

The item to search for in the collection.

Returns:
TypeDescription
Booleantrue if the item is in the collection.
See also:
Example:
// check if a layer is in the map's operational layers.
if (view.map.layers.includes(myLayer)) {
  // ...
}

indexOf(searchElement, fromIndex){Number}

Returns the index of an element in the collection.

Parameters:
searchElement *

Item to search for in the collection.

fromIndex Number
optional

Use if you don't want to search the whole collection or you don't want to search from the start.

Returns:
TypeDescription
NumberThe location of the first match found in the collection, or -1 if there is no match.
See also:
Example:
// index is the index of the first graphic in the
// graphics layer that matches the input graphic
var index = graphicsLayer.graphics.indexOf(graphic);

isCollection(value){Boolean}static

Determines whether the passed value is a Collection.

Parameter:
value *

The value to be checked.

Returns:
TypeDescription
Booleantrue if the test passes, false otherwise.

join(separator){String}

Creates a string representation of the items in the Collection.

Parameter:
separator String
optional

The separator used between each item in the final string. The default is ","

Returns:
TypeDescription
StringThe string representation of the items.
See also:
Example:
var stringCollection = new Collection(["how", "are", "you", "doing?"]);
var phrase = stringCollection.join(" ");

// Prints "how are you doing?"
console.log(phrase);

lastIndexOf(searchElement, fromIndex){Number}

Returns the last index of an element in the collection.

Parameters:
searchElement *

Item to search for in the collection.

fromIndex Number
optional

Use if you don't want to search the whole collection, or you don't want to search from the end.

Returns:
TypeDescription
NumberThe location of the last match found in the collection, or -1 if there is no match.
See also:
Example:
// index is the index of the first graphic in the
// graphics layer that matches the input graphic
var index = graphicsLayer.graphics.lastIndexOf(graphic);

map(callback){Collection}

Passes each Collection item into the callback function and returns a new array of the returned values. For example, if you have a Collection of numbers and would like to add each number by 10, you can use map() to create a new Collection with the same numbers incremented by 10.

Parameter:

The function that processes each item in the Collection and returns a new value at the same index of the original item.

Returns:
TypeDescription
CollectionReturns a new collection containing the new items generated from the callback.
See also:
Example:
// Gets the geometries of the graphics and assigns them to a new Collection
var geoms = graphicsLayer.graphics.map(function(item, i){
  return item.geometry;
});

ofType(type){Object}static

Creates a subclass of Collection containing a typed object.

Parameter:
type Object

The type to assign the Collection.

Returns:
TypeDescription
ObjectThe typed collection.
Example:
require(["esri/core/Collection", "esri/geometry/Point"],
  function(Collection, Point){
    var PointCollection = Collection.ofType(Point);
    var collection = new PointCollection();
    collection.add([-100,40]);
    var point = collection.getItemAt(0);
    // point.x = -100; point.y = 40
});

on(type, listener){Object}

Registers an event handler on the instance. Call this method to hook an event with a listener. See the Events summary table for a list of listened events.

Parameters:
type String

The name of event to listen for.

listener Function

The function to call when the event is fired.

Returns:
TypeDescription
ObjectReturns an event handler with a remove() method that can be called to stop listening for the event.
PropertyTypeDescription
removeFunctionWhen called, removes the listener from the event.
See also:
Example:
view.on("click", function(event){
  // event is the event handle returned after the event fires.
  console.log(event.mapPoint);
});

pop(){*}

Removes the last item from the collection and returns it.

Returns:
TypeDescription
*The last item in the collection.
See also:
Example:
// Removes the last layer in the map and stores it in lastLyr
var lastLyr = map.layers.pop();

push(item){Number}

Adds an item(s) to the end of the collection.

Parameter:
item *

An item or comma-separated list of items to add to the end of the collection.

Returns:
TypeDescription
NumberThe new length of the collection.
See also:
Examples:
// Adds a new graphic to the end of the graphics collection on a GraphicsLayer
graphicsLyr.graphics.push(newGraphic);
// Adds three new graphics to the end of the GraphicsLayer's graphics collection
graphicsLyr.graphics.push(g1, g2, g3);

reduce(callback){*}

Reduces all items in the collection (from left to right) into a single variable using callback.

Parameter:

The function that processes each item in the Collection and appends it to the previous item.

Returns:
TypeDescription
*Returns the value representing the reduction of the Collection's items.
See also:

reduceRight(callback, initialValue){*}

Reduces all items in the collection (from right to left) into a single variable using callback.

Parameters:

The function that processes each item in the Collection and appends it to the previous item.

initialValue *
optional

Item to use as the first element to process in callback.

Returns:
TypeDescription
*Returns the value representing the reduction of the Collection's items.
See also:

remove(item)

Removes an item from the collection. The change event is fired after an item is removed from the Collection.

Parameter:
item *

The item to remove.

Example:
var lyr = map.layers.getItemAt(4);
// Removes the fifth layer from the map
map.layers.remove(lyr);

removeAll()

Removes all items from the collection.

Example:
// Removes all layers from the map
map.layers.removeAll();

removeAt(index){*}

Removes an item from the collection at a specified index. The change event is fired after an item is removed from the Collection.

Parameter:
index Number

The index of the item to remove..

Returns:
TypeDescription
*The removed item if present in the collection, undefined otherwise.
Example:
// Removes the layer at index 4 of the map
map.layers.removeAt(4);

removeMany(items){*}

Removes each item in the input array. If an item is present multiple times in the collection, only the first occurance is removed. The change event is fired after an item is removed from the Collection.

Parameter:
items *[] | Collection

The items to remove.

Returns:
TypeDescription
*The removed item if present in the collection, undefined otherwise.
Example:
var refLayers = [refLyr1, refLyr2, refLyr3];
// Removes three reference layers in the refLayers
// collection from the basemap's referenceLayers
map.basemap.referenceLayers.removeMany(refLayers);

reorder(item, index){*}

Moves an item in the Collection to a specified index. The change event is fired after an item is moved in the Collection.

Parameters:
item *

The item to move.

index Number

The index to move the item to.

Returns:
TypeDescription
*The item that was moved. undefined if item is not in the collection
Example:
// Get the first two layers in a map
var lyr1 = map.layers.getItemAt(0);
var lyr2 = map.layers.getItemAt(1);

// Moves the second layer to the first position in the map.layers Collection
// effectively swapping the positions of lyr1 and lyr2
map.layers.reorder(lyr2, 0);

reverse(){Collection}

Reverses the collection in place.

Returns:
TypeDescription
CollectionThe reversed collection
See also:
Example:
// Reverse layers from the map
map.layers.reverse();

shift(){*}

Removes the first item from the collection (at index 0), and returns it. The remaining items of the collection are then shifted down one index from their previous location.

Returns:
TypeDescription
*The first item in the collection.
See also:
Example:
// Removes the first layer in the map and stores it in firstLyr
var firstLyr = map.layers.shift();

slice(begin, end){Collection}

Creates a new Collection comprised of a portion of the original Collection.

Parameters:
begin Number
optional

The index of the first item to extract.

end Number
optional

The index of the last item to extract.

Returns:
TypeDescription
CollectionReturns a new Collection containing the items in the specified range.
See also:
Example:
// get the graphics from index 50 to 100;
var selection = graphicsLayer.graphics.slice(50, 100);

some(callback){Boolean}

Determines whether an item in the Collection passes a test defined by callback. Each item in the Collection is passed into the callback until one returns a value of true.

Parameter:
callback ItemCallback

The function that defines the test for each Collection item.

Returns:
TypeDescription
BooleanReturns true if any of the items in the Collection pass the test defined in callback. Returns false if all items fail the test.
See also:
Example:
// If at least one of the point graphics has a geometry whose
// elevation is above 1000m, then passes will have a value of true.
// Otherwise, it will be false.
var passes = graphicsLayer.graphics.some(function(item, i){
  return item.geometry.z > 1000;
});

sort(compareFunction)

Sorts the Collection in place.

Parameter:
compareFunction ItemCompareCallback
optional

The function that defines a comparison of two items in the collection.

See also:
Example:
// Sort graphics based on their elevation or z-value
var sortedGraphics = graphicsLayer.graphics.sort(function(a, b){
  if(a.geometry.z > b.geometry.z){
    return 1;
  }
  else if (a.geometry.z < b.geometry.z){
    return -1;
  }
  else {
    return 0;
  }
});

splice(start, deleteCount, items){*[]}

Removes existing items and/or adds new items to the collection.

Parameters:
start Number

Index at which to start changing the collection.

deleteCount Number

Indicates the number of collection items to remove. If 0 is used then no elements are removed and at least one new item should be added in the items parameter.

items *

The item or comma-separated list of items to add to the collection.

Returns:
TypeDescription
*[]An array of the deleted items formerly part of the collection.
See also:
Examples:
// map.layers is a collection of 6 layers
// Adds a seventh layer to the map at index 3
map.layers.splice(3, 0, lyr7);
// Removes two layers starting from index 2 and adds the
// specified layers in the positions of the former layers
var oldLyrs = map.layers.splice(2, 2, lyr8, lyr9, lyr10);

// oldLyrs = [lyr2, lyr3]

toArray(){*[]}

Returns a new array object containing the Collection's items.

Returns:
TypeDescription
*[]An array containing the Collection's items.
Example:
// Creates an array populated with the map's layers
var mapLyrsArray = map.layers.toArray();

unshift(items){Number}

Adds one or more items to the beginning of the collection.

Parameter:
items *

The item(s) to add to the beginning of the collection.

Returns:
TypeDescription
NumberThe new length of the collection.
See also:
Example:
// If a map's basemap has 3 baseLayers: baseLyr0, baseLyr1, baseLyr2
map.basemap.baseLayers.unshift(baseLyr3);

// Now the baseLayers collection is: baseLyr3, baseLyr0, baseLyr1, baseLyr2

Type Definitions

ItemCallback(item, index)

The function that is called for each Collection item.

Parameters:
item *

The current item being assessed in the collection.

index Number

The index of the item being assessed.

ItemCompareCallback(firstItem, secondItem){Number}

The function that defines a comparison.

Parameters:
firstItem *

the first item in the comparison.

secondItem *

the second item in the comparison.

Returns:
TypeDescription
Number-1 if firstItem is smaller than secondItem, 1 if it is larger, and 0 if both are equal.

ItemMapCallback(item, index){*}

The function that defines a mapping and is called for each Collection item.

Parameters:
item *

The current item being assessed in the collection.

index Number

The index of the item being assessed.

Returns:
TypeDescription
*the new value that replaces item.

ItemReduceCallback(previousValue, currentValue, index){*}

The function that defines a reducer.

Parameters:
previousValue *

The item previously reduced value.

currentValue *

The current item being assessed in the collection.

index Number

The index of the item being assessed.

Returns:
TypeDescription
*the value to be passed to the next reducer.

ItemTestCallback(item, index){Boolean}

The function that defines a test and is called for each Collection item.

Parameters:
item *

The current item being assessed in the collection.

index Number

The index of the item being assessed.

Returns:
TypeDescription
Booleantrue if the test passes, false otherwise.

Event Overview

NameTypeSummary
{item: *}

Fires after an item has been added to the collection.

more details
more details

Fires after an item has been added, reordered or removed from the collection.

more details
more details
{item: *}

Fires after an item has been removed from the collection.

more details
more details
{cancellable: Boolean,defaultPrevented: Boolean,item: *,preventDefault: Function}

Fires before an item is added to the collection.

more details
more details
{cancellable: Boolean,defaultPrevented: Boolean,item: *,preventDefault: Function}

Fires before any modifications are performed on the collection.

more details
more details
{cancellable: Boolean,defaultPrevented: Boolean,item: *,preventDefault: Function}

Fires before an item has been removed from the collection.

more details
more details
{added: *[],moved: *[],removed: *[]}

Fires after an item has been added, reordered, or removed from the Collection.

more details
more details

Event Details

after-add

Fires after an item has been added to the collection.

Property:
item *

The item added to the collection.

Example:
// indicates a layer has been added to the map
map.layers.on("after-add", function(event){
  console.log(event.item, " has been added to the map.");
});

after-changes

Fires after an item has been added, reordered or removed from the collection.

Example:
map.layers.on("after-changes", function(event){
  console.log(event, " layer was added/removed from the map.");
});

after-remove

Fires after an item has been removed from the collection.

Property:
item *

The item to remove from the collection.

Example:
// indicates a layer has been removed from the map
map.layers.on("after-remove", function(event){
  console.log(event.item, " has been removed from the map.");
});

before-add

Fires before an item is added to the collection. This event can be used to prevent an item from being added to the collection by cancelling it with the event.preventDefault() method.

Properties:
cancellable Boolean

Indicates if the change event can be cancelled.

defaultPrevented Boolean

Indicates if this event has previously been cancelled by another event handler.

item *

The item to add to the collection.

preventDefault Function

A method that prevents the item from being added to the collection.

Example:
// prevents a layer from being added to the map more than once.
map.layers.on("before-add", function(event){
   if(map.layers.includes(event.item){
     event.preventDefault();
     console.log("layer already exists in map.");
   }
});

before-changes

Fires before any modifications are performed on the collection. This event can be used to prevent an item from being added or removed from the collection by cancelling it with the event.preventDefault() method.

Properties:
cancellable Boolean

Indicates if the change event can be cancelled.

defaultPrevented Boolean

Indicates if this event has previously been cancelled by another event handler.

item *

The item to add or remove from the collection.

preventDefault Function

A method that prevents the item from being added or removed from the collection.

Example:
map.layers.on("before-changes", function(event){
  // prevents layers from being added/removed from the map
  event.preventDefault();
});

before-remove

Fires before an item has been removed from the collection. This event can be used to prevent an item from being removed from the collection by cancelling it with the event.preventDefault() method.

Properties:
cancellable Boolean

Indicates if the change event can be cancelled.

defaultPrevented Boolean

Indicates if this event has previously been cancelled by another event handler.

item *

The item to remove from the collection.

preventDefault Function

A method that prevents the item from being removed from the collection.

Example:
// prevents a layer from being removed from the basemap
map.basemap.baseLayers.on("before-remove", function(event){
   if(map.basemap.baseLayers.includes(event.item)){
     event.preventDefault();
     console.log("layer cannot be removed from basemap.");
   }
});

change

Fires after an item has been added, reordered, or removed from the Collection. Using methods of other classes that affect properties of type Collection will also cause this event to fire, such as Map.add(), Map.remove(), Map.reorder().

For example, map.layers.add(newLyr) and map.add(newLyr) which uses Map.add() to add a new layer to the map.layers collection will cause this event to fire.

Properties of type Collection cannot be watched. The change event should be used to notify the developer/user of changes to the collection.

Properties:
added *[]

An array of items added to the collection using either add() or addMany().

moved *[]

An array of items that moved in the collection using reorder().

removed *[]

An array of items removed from the collection using either remove(), removeMany(), removeAt(), or removeAll().

Example:
// This function will fire each time a layer is either added,
// moved, or removed from the map.layers Collection
map.layers.on("change", function(event){
  var newLayers = event.added; // An array of layers added to the map.layers Collection
  var reorderedLayers = event.moved;  // An array of layers moved in the Collection
  var removedLayers = event.removed;  // An array of layers removed from map
});

API Reference search results

NameTypeModule

There were no match results from your search criteria.