Collections
Introduction
The Collection class provides a fluent, convenient wrapper for working with arrays of data. For example, check out the following code. We'll use the collect helper to create a new collection instance from the array.
- Typescript
- Javascript
import { collect } from "mongoloquent";
const collection = collect(["Ajat", "Udin", null]);
.where("foo", "Ajat")
.map((item) => item.toUpperCase());
import { collect } from "mongoloquent";
const collection = collect(["Ajat", "Udin", null]);
.where("foo", "Ajat")
.map((item) => item.toUpperCase());
As you can see, the Collection class allows you to chain its methods to perform fluent mapping and reducing of the underlying array. In general, collections are immutable, meaning every Collection method returns an entirely new Collection instance.
Creating Collections
As mentioned above, the collect helper returns a new Collection instance for the given array. So, creating a collection is as simple as:
- Typescript
- Javascript
import { collect } from "mongoloquent";
const collection = collect([1, 2, 3])
import { collect } from "mongoloquent";
const collection = collect([1, 2, 3])
You may also create a collection using the make methods.
The results
Mongoloquentqueries array are always returned asCollectioninstances.
Available Methods
For the majority of the remaining collection documentation, we'll discuss each method available on the Collection class. Remember, all of these methods may be chained to fluently manipulate the underlying array. Furthermore, almost every method returns a new Collection instance, allowing you to preserve the original copy of the collection when necessary:
Methods Listing
after()
The after method returns the item after the given item. null is returned if the given item is not found or is the last item:
- Typescript
- Javascript
const collection = collect([1,2,3,4,5])
collection.after(3);
// 4
collection.after(5);
// null
const collection = collect([1,2,3,4,5])
collection.after(3);
// 4
collection.after(5);
// null
This method searches for the given item using "loose" comparison, meaning a string containing an integer value will be considered equal to an integer of the same value. To use "strict" comparison, you may provide the strict argument to the method:
- Typescript
- Javascript
collect([1,2,3,4,5]).after("4", true);
// null
collect([1,2,3,4,5]).after("4", true);
// null
Alternatively, you may provide your own closure to search for the first item that passes a given truth test:
- Typescript
- Javascript
collect([2, 4, 6, 8]).after(function (item) {
return item > 5;
});
// 8
collect([2, 4, 6, 8]).after(function (item) {
return item > 5;
});
// 8
all()
The all method returns the underlying array represented by the collection:
- Typescript
- Javascript
collect([1, 2, 3]).all();
// [1, 2, 3]
collect([1, 2, 3]).all();
// [1, 2, 3]
average()
Alias for the avg method.
avg()
The avg method returns the average value of a given key:
- Typescript
- Javascript
const average = collect([
{foo: 10},
{foo: 10},
{foo: 20},
{foo: 40},
]).avg("foo");
// 20
const average = collect([1, 1, 2, 4]).avg();
// 2
const average = collect([
{foo: 10},
{foo: 10},
{foo: 20},
{foo: 40},
]).avg("foo");
// 20
const average = collect([1, 1, 2, 4]).avg();
// 2
before()
The before method is the opposite of the after method. It returns the item before the given item. null is returned if the given item is not found or is the first item:
- Typescript
- Javascript
const collection = collect([1,2,3,4,5])
collection.before(3);
// 2
collection.before(1);
// null
collection.before("4", true);
// null
collection.before(function (item) {
return item > 5;
});
// 4
const collection = collect([1,2,3,4,5])
collection.before(3);
// 2
collection.before(1);
// null
collection.before("4", true);
// null
collection.before(function (item) {
return item > 5;
});
// 4
chunk()
The chunk method breaks the collection into multiple, smaller collections of a given size:
- Typescript
- Javascript
const collection = collect([1, 2, 3, 4, 5, 6, 7])
const chunks = collection.chunk(4);
chunks.all();
// [[1, 2, 3, 4], [5, 6, 7]]
const collection = collect([1, 2, 3, 4, 5, 6, 7])
const chunks = collection.chunk(4);
chunks.all();
// [[1, 2, 3, 4], [5, 6, 7]]
collect()
The collect method returns a new Collection instance with the items currently in the collection:
- Typescript
- Javascript
const collectionA = collect([1, 2, 3]);
const collectionB = collectionA.collect();
collectionB.all();
// [1, 2, 3]
const collectionA = collect([1, 2, 3]);
const collectionB = collectionA.collect();
collectionB.all();
// [1, 2, 3]
concat()
The concat method appends the given array or collection's values onto the end of another collection:
- Typescript
- Javascript
const collection = collect(["Jhon Doe"])
const concatenated = collection.concat(["Jane Doe"]).concat([
"Jhonny Doe",
])
concatenated.all();
// ["Jhon Doe", "Jane Doe", "Jhonny Doe"]
const collection = collect(["Jhon Doe"])
const concatenated = collection.concat(["Jane Doe"]).concat([
"Jhonny Doe",
])
concatenated.all();
// ["Jhon Doe", "Jane Doe", "Jhonny Doe"]
contains()
The contains method determines whether the collection contains a given item. You may pass a closure to the contains method to determine if an element exists in the collection matching a given truth test:
- Typescript
- Javascript
const collection = collect([1, 2, 3, 4, 5]);
collection.contains((item) => {
return item > 5;
});
// false
const collection = collect([1, 2, 3, 4, 5]);
collection.contains((item) => {
return item > 5;
});
// false
Alternatively, you may pass a string to the contains method to determine whether the collection contains a given item value:
- Typescript
- Javascript
const collection = collect([{name: "Desk", price: 100}]);
collection.contains("Desk")
// true
collection.contains("New York")
// false
const collection = collect([{name: "Desk", price: 100}]);
collection.contains("Desk")
// true
collection.contains("New York")
// false
You may also pass a key / value pair to the contains method, which will determine if the given pair exists in the collection:
- Typescript
- Javascript
const collection = collect([
{product: "Desk", price: 200}
{product: "Chair", price: 100}
]);
collection.contains("product", "Bookcase");
// false
const collection = collect([
{product: "Desk", price: 200}
{product: "Chair", price: 100}
]);
collection.contains("product", "Bookcase");
// false
The contains method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the containsStrict method to filter using "strict" comparisons.
For the inverse of
contains, see the doesntContain method.
containsStrict()
This method has the same signature as the contains method; however, all values are compared using "strict" comparisons.
count()
The count method returns the total number of items in the collection:
- Typescript
- Javascript
const collection = collect([1, 2, 3, 4]);
collection.count();
// 4
const collection = collect([1, 2, 3, 4]);
collection.count();
// 4
countBy()
The countBy method counts the occurrences of values in the collection. By default, the method counts the occurrences of every element, allowing you to count certain "types" of elements in the collection:
- Typescript
- Javascript
const collection = collect([1, 2, 2, 2, 3]);
const counted = collection.countBy();
counted.all();
// {1: 1, 2: 3, 3: 1}
const collection = collect([1, 2, 2, 2, 3]);
const counted = collection.countBy();
counted.all();
// {1: 1, 2: 3, 3: 1}
You may pass a closure to the countBy method to count all items by a custom value:
- Typescript
- Javascript
const collection = collect(["alice@gmail.com", "bob@yahoo.com", "carlos@gmail.com",]);
const counted = collection.countBy((item) => {
return item.email.split("@")[1];
});
counted.all();
// {gmail.com: 2, yahoo.com: 1}
const collection = collect(["alice@gmail.com", "bob@yahoo.com", "carlos@gmail.com",]);
const counted = collection.countBy((item) => {
return item.email.split("@")[1];
});
counted.all();
// {gmail.com: 2, yahoo.com: 1}
doesntContain()
The doesntContain method determines whether the collection does not contain a given item. You may pass a closure to the doesntContain method to determine if an element does not exist in the collection matching a given truth test:
- Typescript
- Javascript
const collection = collect([1, 2, 3, 4, 5]);
collection.doesntContain((item) => {
return item < 5;
});
// false
const collection = collect([1, 2, 3, 4, 5]);
collection.doesntContain((item) => {
return item < 5;
});
// false
Alternatively, you may pass a string to the doesntContain method to determine whether the collection does not contain a given item value:
- Typescript
- Javascript
const collection = collect([
{product: "Desk", price: 200}
]);
collection.doesntContain("Table");
// true
collection.doesntContain("Desk");
// false
const collection = collect([
{product: "Desk", price: 200}
]);
collection.doesntContain("Table");
// true
collection.doesntContain("Desk");
// false
You may also pass a key / value pair to the doesntContain method, which will determine if the given pair does not exist in the collection:
- Typescript
- Javascript
const collection = collect([
{product: "Desk", price: 200}
{product: "Chair", price: 100}
]);
collection.doesntContain("product", "Bookcase");
// true
const collection = collect([
{product: "Desk", price: 200}
{product: "Chair", price: 100}
]);
collection.doesntContain("product", "Bookcase");
// true
duplicates()
The duplicates method retrieves and returns duplicate values from the collection:
- Typescript
- Javascript
const collection = collect(["a", "b", "a", "c", "b"]);
collection.duplicates();
// {2: "a", 4: "b"}
const collection = collect(["a", "b", "a", "c", "b"]);
collection.duplicates();
// {2: "a", 4: "b"}
If the collection contains arrays or objects, you can pass the key of the attributes that you wish to check for duplicate values:
- Typescript
- Javascript
const collection = collect([
{ email: "abigail@example.com", position: "Developer" },
{ email: "james@example.com", position: "Designer" },
{ email: "victoria@example.com", position: "Developer" },
]);
collection.duplicates("position");
// {2: "Developer"}
const collection = collect([
{ email: "abigail@example.com", position: "Developer" },
{ email: "james@example.com", position: "Designer" },
{ email: "victoria@example.com", position: "Developer" },
]);
collection.duplicates("position");
// {2: "Developer"}
each()
The each method iterates over the items in the collection and passes each item to a closure:
- Typescript
- Javascript
const collection = collect([1, 2, 3, 4]);
collection.each((item) => {
// ...
});
const collection = collect([1, 2, 3, 4]);
collection.each((item) => {
// ...
});
If you would like to stop iterating through the items, you may return false from your closure:
- Typescript
- Javascript
collection.each((item) => {
if (/* condition */) {
return false;
}
});
collection.each((item) => {
if (/* condition */) {
return false;
}
});
isEvery()
The isEvery method may be used to verify that all elements of a collection pass a given truth test:
- Typescript
- Javascript
collect([1, 2, 3, 4]).isEvery((item) => {
return item > 2;
});
// false
collect([1, 2, 3, 4]).isEvery((item) => {
return item > 2;
});
// false
If the collection is empty, the isEvery method will return true:
- Typescript
- Javascript
const collection = collect([])
collection.isEvery((item) => {
return item.foo > 2;
});
// true
const collection = collect([])
collection.isEvery((item) => {
return item.foo > 2;
});
// true
except()
The except method returns all items in the collection except for those with the specified keys:
- Typescript
- Javascript
const collection = collect([
{productId: 1, price: 100, discount: false},
]);
const filtered = collection.except(["price", "discount"]);
filtered.all();
// {productId: 1}
const collection = collect([
{productId: 1, price: 100, discount: false},
]);
const filtered = collection.except(["price", "discount"]);
filtered.all();
// {productId: 1}
For the inverse of except, see the only method.
first()
The first method returns the first element in the collection that passes a given truth test:
- Typescript
- Javascript
collect([1, 2, 3, 4]).first((item) => {
return item > 2;
});
// 3
collect([1, 2, 3, 4]).first((item) => {
return item > 2;
});
// 3
You may also call the first method with no arguments to get the first element in the collection. If the collection is empty, null is returned:
- Typescript
- Javascript
collect([1, 2, 3, 4]).first();
// 1
collect([1, 2, 3, 4]).first();
// 1
firstOrFail()
The firstOrFail method is identical to the first method; however, if no result is found, MongoloquentItemNotFoundException exception will be thrown:
- Typescript
- Javascript
collect([1, 2, 3, 4]).first(item => {
return item.foo > 5;
});
// MongoloquentItemNotFoundException
collect([1, 2, 3, 4]).first(item => {
return item.foo > 5;
});
// MongoloquentItemNotFoundException
You may also call the firstOrFail method with no arguments to get the first element in the collection. If the collection is empty, an MongoloquentItemNotFoundException exception will be thrown:
- Typescript
- Javascript
collect([]).first(item => {
return item.foo > 5;
});
// MongoloquentItemNotFoundException
collect([]).first(item => {
return item.foo > 5;
});
// MongoloquentItemNotFoundException
firstWhere()
The firstWhere method returns the first element in the collection with the given key / value pair:
- Typescript
- Javascript
const collection = collect([
{name: "Regena", age: null},
{name: "Linda", age: 14},
{name: "Diego", age: 23},
{name: "Linda", age: 84},
]);
collection.firstWhere("name", "Linda");
// {name: "Linda", age: 14}
const collection = collect([
{name: "Regena", age: null},
{name: "Linda", age: 14},
{name: "Diego", age: 23},
{name: "Linda", age: 84},
]);
collection.firstWhere("name", "Linda");
// {name: "Linda", age: 14}
You may also call the firstWhere method with a comparison operator:
- Typescript
- Javascript
collection.firstWhere("age", ">=", 18);
// {name: "Diego", age: 23}
collection.firstWhere("age", ">=", 18);
// {name: "Diego", age: 23}
Like the where method, you may pass one argument to the firstWhere method. In this scenario, the firstWhere method will return the first item where the given item key's value is "truthy":
- Typescript
- Javascript
collection.firstWhere("age");
// {name: "Linda", age: 14}
collection.firstWhere("age");
// {name: "Linda", age: 14}
forget()
The forget method removes an item from the collection by its key:
- Typescript
- Javascript
const collection = collect([{name: "Ajat", framework: "Mongoloquent"}]);
// Forget a single key
collection.forget("name");
// {framework: "Mongoloquent"}
// Forget multiple keys
collection.forget(["name", "framework"]);
// {}
const collection = collect([{name: "Ajat", framework: "Mongoloquent"}]);
// Forget a single key
collection.forget("name");
// {framework: "Mongoloquent"}
// Forget multiple keys
collection.forget(["name", "framework"]);
// {}
Unlike most other collection methods,
forgetdoes not return a new modified collection; it modifies and returns the collection it is called on.
forPage()
The forPage method returns a new collection containing the items that would be present on a given page number. The method accepts the page number as its first argument and the number of items to show per page as its second argument:
- Typescript
- Javascript
const collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
const chunk = collection.forPage(2, 3);
chunk.all();
// [4, 5, 6]
const collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
const chunk = collection.forPage(2, 3);
chunk.all();
// [4, 5, 6]
get()
The get method returns the item at a given key. If the key does not exist, null is returned:
- Typescript
- Javascript
const collection = collect([{name: "ajat", framework: "mongoloquent"}])
collection.get("name");
// "ajat"
const collection = collect([{name: "ajat", framework: "mongoloquent"}])
collection.get("name");
// "ajat"
You may optionally pass a default value as the second argument:
- Typescript
- Javascript
const collection = collect([{name: "ajat", framework: "mongoloquent"}])
collection.get("age", 34);
// 34
const collection = collect([{name: "ajat", framework: "mongoloquent"}])
collection.get("age", 34);
// 34
You may even pass a callback as the method's default value. The result of the callback will be returned if the specified key does not exist:
- Typescript
- Javascript
const collection = collect([{name: "ajat", framework: "mongoloquent"}])
collection.get("email", () => {
return "ajat@example.com";
});
// ajat@example.com
const collection = collect([{name: "ajat", framework: "mongoloquent"}])
collection.get("email", () => {
return "ajat@example.com";
});
// ajat@example.com
groupBy()
The groupBy method groups the collection's items by a given key:
- Typescript
- Javascript
const collection = collect([
{ accountId: "account-x10", product: "Chair" },
{ accountId: "account-x10", product: "Bookcase" },
{ accountId: "account-x11", product: "Desk" },
]);
const grouped = collection.groupBy("accountId");
grouped.all();
/*
[
{
"account-x10": [
{
"accountId": "account-x10",
"product": "Chair"
},
{
"accountId": "account-x10",
"product": "Bookcase"
}
]
},
{
"account-x11": [
{
"accountId": "account-x11",
"product": "Desk"
}
]
}
]
*/
const collection = collect([
{ accountId: "account-x10", product: "Chair" },
{ accountId: "account-x10", product: "Bookcase" },
{ accountId: "account-x11", product: "Desk" },
]);
const grouped = collection.groupBy("accountId");
grouped.all();
/*
[
{
"account-x10": [
{
"accountId": "account-x10",
"product": "Chair"
},
{
"accountId": "account-x10",
"product": "Bookcase"
}
]
},
{
"account-x11": [
{
"accountId": "account-x11",
"product": "Desk"
}
]
}
]
*/
Instead of passing a string key, you may pass a callback. The callback should return the value you wish to key the group by:
- Typescript
- Javascript
const grouped = collection.groupBy((item => {
return item.accountId.substring(8);
}));
grouped.all();
/*
[
{
"x10": [
{
"accountId": "account-x10",
"product": "Chair"
},
{
"accountId": "account-x10",
"product": "Bookcase"
}
]
},
{
"x11": [
{
"accountId": "account-x11",
"product": "Desk"
}
]
}
]
*/
const grouped = collection.groupBy((item => {
return item.accountId.substring(8);
}));
grouped.all();
/*
[
{
"x10": [
{
"accountId": "account-x10",
"product": "Chair"
},
{
"accountId": "account-x10",
"product": "Bookcase"
}
]
},
{
"x11": [
{
"accountId": "account-x11",
"product": "Desk"
}
]
}
]
*/
has()
The has method determines if a given key exists in the collection:
- Typescript
- Javascript
const collection = collect([{accountId: 1, product: "Desk", amount: 5}]);
collection.has("product");
// true
collection.has(["product", "amount"]);
// true
collection.has("amount", "price");
// false
const collection = collect([{accountId: 1, product: "Desk", amount: 5}]);
collection.has("product");
// true
collection.has(["product", "amount"]);
// true
collection.has("amount", "price");
// false
hasAny()
The hasAny method determines whether any of the given keys exist in the collection:
- Typescript
- Javascript
const collection = collect([{accountId: 1, product: "Desk", amount: 5}]);
collection.hasAny(["product", "price"]);
// true
collection.hasAny(["name", "price"]);
// false
const collection = collect([{accountId: 1, product: "Desk", amount: 5}]);
collection.hasAny(["product", "price"]);
// true
collection.hasAny(["name", "price"]);
// false
implode()
The implode method joins items in a collection. Its arguments depend on the type of items in the collection. If the collection contains arrays or objects, you should pass the key of the attributes you wish to join, and the "glue" string you wish to place between the values:
- Typescript
- Javascript
const collection = collect([
{accountId: 1, product: "Desk"},
{accountId: 2, product: "Chair"},
]);
collection.implode("product", ", ");
// "Desk, Chair"
const collection = collect([
{accountId: 1, product: "Desk"},
{accountId: 2, product: "Chair"},
]);
collection.implode("product", ", ");
// "Desk, Chair"
If the collection contains simple strings or numeric values, you should pass the "glue" as the only argument to the method:
- Typescript
- Javascript
const collection = collect([1, 2, 3, 4, 5]);
collection.implode("-");
// "1-2-3-4-5"
const collection = collect([1, 2, 3, 4, 5]);
collection.implode("-");
// "1-2-3-4-5"
You may pass a closure to the implode method if you would like to format the values being imploded:
- Typescript
- Javascript
collection.implode((item) => {
return item.product.toUpperCase();
}, ", ");
// "DESK, CHAIR"
collection.implode((item) => {
return item.product.toUpperCase();
}, ", ");
// "DESK, CHAIR"
isEmpty()
The isEmpty method returns true if the collection is empty; otherwise, false is returned:
- Typescript
- Javascript
collect([]).isEmpty();
// true
collect([]).isEmpty();
// true
isNotEmpty()
The isNotEmpty method returns true if the collection is not empty; otherwise, false is returned:
- Typescript
- Javascript
collect([]).isNotEmpty();
// false
collect([]).isNotEmpty();
// false
keyBy()
The keyBy method keys the collection by the given key. If multiple items have the same key, only the last one will appear in the new collection:
- Typescript
- Javascript
const collection = collect([
{productId: "prod-100", product: "Desk"},
{productId: "prod-200", product: "Chair"},
]);
const keyed = collection.keyBy("productId");
/*
{
"prod-100": {
productId: "prod-100",
product: "Desk",
},
"prod-200": {
productId: "prod-200",
product: "Chair",
},
}
*/
const collection = collect([
{productId: "prod-100", product: "Desk"},
{productId: "prod-200", product: "Chair"},
]);
const keyed = collection.keyBy("productId");
/*
{
"prod-100": {
productId: "prod-100",
product: "Desk",
},
"prod-200": {
productId: "prod-200",
product: "Chair",
},
}
*/
You may also pass a callback to the method. The callback should return the value to key the collection by:
- Typescript
- Javascript
const keyed = collection.keyBy((item => {
return item.productId.toUpperCase();
}));
/*
{
"PROD-100": {
productId: "prod-100",
product: "Desk",
},
"PROD-200": {
productId: "prod-200",
product: "Chair",
},
}
*/
const keyed = collection.keyBy((item => {
return item.productId.toUpperCase();
}));
/*
{
"PROD-100": {
productId: "prod-100",
product: "Desk",
},
"PROD-200": {
productId: "prod-200",
product: "Chair",
},
}
*/
last()
The last method returns the last element in the collection that passes a given truth test:
- Typescript
- Javascript
collect([1, 2, 3, 4]).last((item) => {
return item.foo < 3;
});
// 2
collect([1, 2, 3, 4]).last((item) => {
return item.foo < 3;
});
// 2
You may also call the last method with no arguments to get the last element in the collection. If the collection is empty, null is returned:
- Typescript
- Javascript
collect([1, 2, 3, 4]).last();
// 4
collect([1, 2, 3, 4]).last();
// 4
make()
The static make method creates a new collection instance. See the Creating Collections section.
- Typescript
- Javascript
import { Collection } from "mongoloquent";
const collection = Collection.make([1, 2, 3, 4]);
import { Collection } from "mongoloquent";
const collection = Collection.make([1, 2, 3, 4]);
max()
The max method returns the maximum value of a given key:
- Typescript
- Javascript
const max = collect([
{foo: 10},
{foo: 20},
]).max("foo");
// 20
const max = collect([1, 2, 3, 4]).max();
// 4
const max = collect([
{foo: 10},
{foo: 20},
]).max("foo");
// 20
const max = collect([1, 2, 3, 4]).max();
// 4
median()
The median method returns the median value of a given key:
- Typescript
- Javascript
const median = collect([
{foo: 10},
{foo: 10},
{foo: 20},
{foo: 40},
]).median("foo");
// 15
const median = collect([1, 1, 2, 4]).median();
// 1.5
const median = collect([
{foo: 10},
{foo: 10},
{foo: 20},
{foo: 40},
]).median("foo");
// 15
const median = collect([1, 1, 2, 4]).median();
// 1.5
min()
The min method returns the minimum value of a given key:
- Typescript
- Javascript
const min = collect([
{foo: 10},
{foo: 20},
]).min("foo");
// 10
const min = collect<IData>([1, 2, 3, 4, 5]).min();
// 1
const min = collect([
{foo: 10},
{foo: 20},
]).min("foo");
// 10
const min = collect<IData>([1, 2, 3, 4, 5]).min();
// 1
multiply()
The multiply method creates the specified number of copies of all items in the collection:
- Typescript
- Javascript
const users = collect<IData>([
{name: "User #1", email: "user1@example.com"},
{name: "User #2", email: "user2@example.com"}
]).multiply(3);
/*
[
{name: "User #1", email: "user1@example.com"},
{name: "User #2", email: "user2@example.com"},
{name: "User #1", email: "user1@example.com"},
{name: "User #2", email: "user2@example.com"},
{name: "User #1", email: "user1@example.com"},
{name: "User #2", email: "user2@example.com"}
]
*/
const users = collect<IData>([
{name: "User #1", email: "user1@example.com"},
{name: "User #2", email: "user2@example.com"}
]).multiply(3);
/*
[
{name: "User #1", email: "user1@example.com"},
{name: "User #2", email: "user2@example.com"},
{name: "User #1", email: "user1@example.com"},
{name: "User #2", email: "user2@example.com"},
{name: "User #1", email: "user1@example.com"},
{name: "User #2", email: "user2@example.com"}
]
*/
nth()
The nth method creates a new collection consisting of every n-th element:
- Typescript
- Javascript
const collection = collect(["a", "b", "c", "d", "e", "f"]);
collection.nth(4);
// ["a", "e"]
const collection = collect(["a", "b", "c", "d", "e", "f"]);
collection.nth(4);
// ["a", "e"]
You may optionally pass a starting offset as the second argument:
- Typescript
- Javascript
collection.nth(4, 1);
// [b, f]
collection.nth(4, 1);
// [b, f]
only()
The only method returns the items in the collection with the specified keys:
- Typescript
- Javascript
const collection = collect([
{
productId: 1,
name: "Desk",
price: 100,
discount: false,
},
]);
const filtered = collection.only(["productId", "name"]);
filtered.all();
// {productId: 1, name: "Desk"}
const collection = collect([
{
productId: 1,
name: "Desk",
price: 100,
discount: false,
},
]);
const filtered = collection.only(["productId", "name"]);
filtered.all();
// {productId: 1, name: "Desk"}
For the inverse of only, see the except method.
pluck()
The pluck method retrieves all of the values for a given key:
- Typescript
- Javascript
const collection = collect([
{productId: 1, name: "Desk"},
{productId: 2, name: "Chair"},
]);
const plucked = collection.pluck("name");
plucked.all();
// ["Desk", "Chair"]
const collection = collect([
{productId: 1, name: "Desk"},
{productId: 2, name: "Chair"},
]);
const plucked = collection.pluck("name");
plucked.all();
// ["Desk", "Chair"]
You may also pass multiple keys to the pluck method.
- Typescript
- Javascript
const collection = collect([
{productId: 1, name: "Desk"},
{productId: 2, name: "Chair"},
]);
const plucked = collection.pluck("name", "productId");
plucked.all();
/*
{
"mame": "Desk",
"productId": 1
},
{
"mame": "Chair",
"productId": 2
}
*/
const collection = collect([
{productId: 1, name: "Desk"},
{productId: 2, name: "Chair"},
]);
const plucked = collection.pluck("name", "productId");
plucked.all();
/*
{
"mame": "Desk",
"productId": 1
},
{
"mame": "Chair",
"productId": 2
}
*/
pull()
The pull method removes and returns an item from the collection by its key:
- Typescript
- Javascript
const collection = collect<IData>([{productId: "prod-100", name: "Desk"}]);
collection.pull("name");
// Desk
collection.all();
// {productId: "prod-100"}
const collection = collect([{productId: "prod-100", name: "Desk"}]);
collection.pull("name");
// Desk
collection.all();
// {productId: "prod-100"}
random()
The random method returns a random item from the collection:
- Typescript
- Javascript
const collection = collect([1, 2, 3, 4, 5]);
collection.random();
// 4 - (retrived randomly)
const collection = collect([1, 2, 3, 4, 5]);
collection.random();
// 4 - (retrived randomly)
You may pass an integer to random to specify how many items you would like to randomly retrieve. A collection of items is always returned when explicitly passing the number of items you wish to receive:
- Typescript
- Javascript
const random = collection.random(3)
// [2, 4, 5] - (retrived randomly)
const random = collection.random(3)
// [2, 4, 5] - (retrived randomly)
If the collection instance has fewer items than requested, the random method will throw an MongoloquentInvalidArgumentException.
select()
The select method selects the given keys from the collection, similar to an SQL SELECT statement:
- Typescript
- Javascript
const users = collect([
{name: "Ajat Darojat", role: "Developer", status: "active"},
{name: "Udin", role: "Developer", status: "active"},
]);
users.select(["name", "role"]).all();
/*
[
{name: "Ajat Darojat", role: "Developer"},
{name: "Udin", role: "Developer"},
]
*/
const users = collect([
{name: "Ajat Darojat", role: "Developer", status: "active"},
{name: "Udin", role: "Developer", status: "active"},
]);
users.select(["name", "role"]).all();
/*
[
{name: "Ajat Darojat", role: "Developer"},
{name: "Udin", role: "Developer"},
]
*/
shuffle()
The shuffle method randomly shuffles the items in the collection:
- Typescript
- Javascript
const collection = collect([1, 2, 3, 4, 5]);
const shuffled = collection.shuffle();
shuffled.all();
// [4, 1, 3, 5, 2] - (retrived randomly)
const collection = collect([1, 2, 3, 4, 5]);
const shuffled = collection.shuffle();
shuffled.all();
// [4, 1, 3, 5, 2] - (retrived randomly)
skip()
The skip method returns a new collection, with the given number of elements removed from the beginning of the collection:
- Typescript
- Javascript
const collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
const skipped = collection.skip(4);
skipped.all();
// [5, 6, 7, 8, 9, 10]
const collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
const skipped = collection.skip(4);
skipped.all();
// [5, 6, 7, 8, 9, 10]
skipUntil()
The skipUntil method skips over items from the collection while the given callback returns false. Once the callback returns true all of the remaining items in the collection will be returned as a new collection:
- Typescript
- Javascript
const collection = collect([1, 2, 3, 4]);
const subset = collection.skipUntil((item) => {
return item >= 3;
});
subset.all();
// [3, 4]
const collection = collect([1, 2, 3, 4]);
const subset = collection.skipUntil((item) => {
return item >= 3;
});
subset.all();
// [3, 4]
If the given value is not found or the callback never returns
true, theskipUntilmethod will return an empty collection.
skipWhile()
The skipWhile method skips over items from the collection while the given callback returns true. Once the callback returns false all of the remaining items in the collection will be returned as a new collection:
- Typescript
- Javascript
const collection = collect([1, 2, 3, 4, 5]);
const subset = collection.skipWhile((item) => {
return item.foo <= 3;
});
subset.all();
// [4, 5]
const collection = collect([1, 2, 3, 4, 5]);
const subset = collection.skipWhile((item) => {
return item.foo <= 3;
});
subset.all();
// [4, 5]
If the callback never returns
false, theskipWhilemethod will return an empty collection.
sliding()
The sliding method returns a new collection of chunks representing a "sliding window" view of the items in the collection:
- Typescript
- Javascript
const collection = collect([1, 2, 3, 4, 5]);
const chunks = collection.sliding(2);
chunks.all();
/*
[
[1, 2],
[2, 3],
[3, 4],
[4, 5],
]
*/
const collection = collect([1, 2, 3, 4, 5]);
const chunks = collection.sliding(2);
chunks.all();
/*
[
[1, 2],
[2, 3],
[3, 4],
[4, 5],
]
*/
You may optionally pass a second "step" value, which determines the distance between the first item of every chunk:
- Typescript
- Javascript
const collection = collect([1, 2, 3, 4, 5]);
const chunks = collection.sliding(3, 2);
chunks.all();
/*
[
[1, 2, 3],
[3, 4, 5],
]
*/
const collection = collect([1, 2, 3, 4, 5]);
const chunks = collection.sliding(3, 2);
chunks.all();
/*
[
[1, 2, 3],
[3, 4, 5],
]
*/