Convenient and dependency free wrapper for working with arrays and objects
npm install collect.js --save
Using Laravel as your backend? Collect.js offers an (almost) identical api to Laravel Collections 5.4. See differences.
All available methods
- all
- average
- chunk
- collapse
- combine
- contains
- count
- diff
- diffKeys
- each
- every
- except
- filter
- first
- flatMap
- flatten
- flip
- forget
- forPage
- get
- groupBy
- has
- implode
- intersect
- isEmpty
- isNotEmpty
- keyBy
- keys
- last
- map
- mapWithKeys
- max
- median
- merge
- min
- mode
- nth
- only
- partition
- pipe
- pluck
- pop
- prepend
- pull
- push
- put
- random
- reduce
- reject
- reverse
- search
- shift
- shuffle
- slice
- sort
- sortBy
- sortByDesc
- splice
- split
- sum
- take
- tap
- times
- toArray
- toJson
- transform
- union
- unique
- values
- when
- where
- whereIn
- whereInLoose
- whereNotIn
- whereStrict
- zip
All comparisons in collect.js
are done using strict equality. Using loose equality comparisons are generally frowned upon in JavaScript. Laravel only performs "loose" comparisons by default and offer several "strict" comparison methods. These methods have not been implemented in collect.js
because all methods are strict by default.
usecontainsStrict
contains()
usetoArray
all()
useuniqueStrict
unique()
usewhereStrict
where()
usewhereInStrict
whereIn()
usewhereNotInStrict
whereNotIn()
The all method returns the underlying array represented by the collection:
collect([1, 2, 3]).all();
//=> [1, 2, 3]
Alias for the avg()
method
The avg method returns the average of all items in the collection:
collect([1, 3, 3, 7]).avg();
//=> 3.5
If the collection contains nested arrays or objects, you should pass a key to use for determining which values to calculate the average:
const collection = collect([{
name: 'JavaScript: The Good Parts', pages: 176
}, {
name: 'JavaScript: The Definitive Guide', pages: 1096
}]);
collection.avg('pages');
//=> 636
The chunk method breaks the collection into multiple, smaller collections of a given size:
const collection = collect([1, 2, 3, 4, 5, 6, 7]);
const chunks = collection.chunk(4);
chunks.all();
//=> [[1, 2, 3, 4], [5, 6, 7]]
The collapse method collapses a collection of arrays into a single, flat collection:
const collection = collect([[1], [{}, 5, {}], ['xoxo']]);
const collapsed = collection.collapse();
collapsed.all();
//=> [1, {}, 5, {}, 'xoxo']
const collection = collect([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
const collapsed = collection.collapse();
collapsed.all();
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
The combine method combines the keys of the collection with the values of another array or collection:
const collection = collect(['name', 'number']);
const combine = collection.combine(['Steven Gerrard', 8]);
combine.all();
//=> {
//=> name: 'Steven Gerrard',
//=> number: 8
//=> }
The contains method determines whether the collection contains a given item:
const collection = collect({
name: 'Steven Gerrard',
number: 8
});
collection.contains('name');
//=> true
collection.contains('age');
//=> false
You may also work with arrays
const collection = collect([1, 2, 3]);
collection.contains(3);
//=> true
You may also pass a key / value pair to the contains method, which will determine if the given pair exists in the collection:
const collection = collect({
name: 'Steven Gerrard',
number: 8
});
collection.contains('name', 'Steve Jobs');
//=> false
Finally, you may also pass a callback to the contains method to perform your own truth test:
const collection = collect([1, 2, 3, 4, 5]);
collection.contains(function (value, key) {
return value > 5;
});
//=> false
The count method returns the total number of items in the collection:
const collection = collect([1, 2, 3, 4]);
collection.count();
//=> 4
The diff method compares the collection against another collection or a plain array based on its values. This method will return the values in the original collection that are not present in the given collection:
const collection = collect([1, 2, 3, 4, 5]);
const diff = collection.diff([1, 2, 3, 9]);
diff.all();
//=> [4, 5]
The diffKeys method compares the collection against another collection or a plain object based on its keys. This method will return the key / value pairs in the original collection that are not present in the given collection:
const collection = collect({
a: 'a',
b: 'b',
c: 'c',
d: 'd'
});
const diff = collection.diffKeys({
b: 'b',
d: 'd'
});
diff.all();
//=> {a: 'a', c: 'c'}
The each method iterates over the items in the collection and passes each item to a callback:
let sum = 0;
const collection = collect([1, 3, 3, 7]);
collection.each(function (item) {
sum += item;
});
//=> console.log(sum);
//=> 14
If you would like to stop iterating through the items, you may return false from your callback:
let sum = 0;
const collection = collect([1, 3, 3, 7]);
collection.each(function (item) {
if (item > 3) {
return false;
}
sum += item;
});
//=> console.log(sum);
//=> 7
The every method may be used to verify that all elements of a collection pass a given truth test:
collect([1, 2, 3, 4]).every(function (value, key) {
return value > 2;
});
//=> false
The except method returns all items in the collection except for those with the specified keys:
const collection = collect({
product_id: 1,
price: 100,
discount: false
});
const filtered = collection.except(['price', 'discount']);
filtered.all();
//=> {product_id: 1}
For the inverse of
except
, see theonly
method.
The filter method filters the collection using the given callback, keeping only those items that pass a given truth test:
const collection = collect([1, 2, 3, 4]);
const filtered = collection.filter(function (value, key) {
return value > 2;
});
filtered.all();
//=> [3, 4]
For the inverse of
filter
, see thereject
method.
The first method returns the first element in the collection that passes a given truth test:
collect([1, 2, 3, 4).first(function (item) {
return item > 1;
});
//=> 2
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:
collect([1, 2, 3, 4]).first();
//=> 1
The flatMap method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items. Then, the array is flattened by a level:
const collection = collect({
name: 'Robbie Fowler',
nickname: 'The God',
position: 'Striker'
});
const flatMapped = collection.flatMap(function (values) {
return values.map(function (value) {
return value.toUpperCase();
});
});
flatMapped.all();
//=> {
//=> name: 'ROBBIE FOWLER',
//=> nickname: 'THE GOD',
//=> position: 'STRIKER'
//=> }
The flatten method flattens a multi-dimensional collection into a single dimension:
const collection = collect({
club: 'Liverpool',
players: ['Sturridge', 'Firmino', 'Coutinho']
});
const flattened = collection.flatten();
flattened.all();
//=> ['Liverpool', 'Sturridge', 'Firmino', 'Coutinho'];
You may optionally pass the function a "depth" argument:
const collection = collect({
Apple: [{
name: 'iPhone 6S',
brand: 'Apple'
}],
Samsung: [{
name: 'Galaxy S7',
brand: 'Samsung'
}]
});
const flattened = collection.flatten(1);
flattened.all();
//=> [
//=> {name: 'iPhone 6S', brand: 'Apple'},
//=> {name: 'Galaxy S7', brand: 'Samsung'}
//=> ]
In this example, calling flatten without providing the depth would have also flattened the nested arrays, resulting in ['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']
. Providing a depth allows you to restrict the levels of nested arrays that will be flattened.
The flip method swaps the collection's keys with their corresponding values:
const collection = collect({
name: 'Steven Gerrard',
number: 8
});
const flipped = collection.flip();
flipped.all();
//=> {
//=> 'Steven Gerrard': 'name',
//=> '8': 'number'
//=> }
The forget method removes an item from the collection by its key:
const collection = collect({
name: 'Steven Gerrard',
number: 8
});
collection.forget('number');
collection.all();
//=> {
//=> name: 'Steven Gerrard'
//=> }
Unlike most other collection methods, forget does not return a new modified collection; it modifies the collection it is called on.
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:
const collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
const forPage = collection.forPage(2, 3);
forPage.all();
//=> [4, 5, 6]
The get method returns the item at a given key. If the key does not exist, null
is returned:
const collection = collect({
firstname: 'Chuck',
lastname: 'Norris'
});
collection.get('lastname');
//=> Norris
collection.get('middlename');
//=> null
You may optionally pass a default value as the second argument:
const collection = collect({
firstname: 'Chuck',
lastname: 'Norris'
});
collection.get('middlename', 'default-value');
//=> default-value
You may even pass a callback as the default value. The result of the callback will be returned if the specified key does not exist:
const collection = collect({
firstname: 'Chuck',
lastname: 'Norris'
});
collection.get('middlename', function () {
return 'default-value';
});
//=> default-value
The groupBy method groups the collection's items by a given key:
const collection = collect([
{
product: 'Chair',
manufacturer: 'IKEA'
},
{
product: 'Desk',
manufacturer: 'IKEA'
},
{
product: 'Chair',
manufacturer: 'Herman Miller'
}
]);
const grouped = collection.groupBy('manufacturer');
grouped.all();
//=> {
//=> IKEA: [
//=> {
//=> id: 100,
//=> product: 'Chair',
//=> manufacturer: 'IKEA',
//=> price: '1490 NOK'
//=> },
//=> {
//=> id: 150,
//=> product: 'Desk',
//=> manufacturer: 'IKEA',
//=> price: '900 NOK'
//=> }
//=> ],
//=> 'Herman Miller': [
//=> {
//=> id: 200,
//=> product: 'Chair',
//=> manufacturer: 'Herman Miller',
//=> price: '9990 NOK'
//=> }
//=> ]
//=> }
In addition to passing a string key, you may also pass a callback. The callback should return the value you wish to key the group by:
const collection = collect([
{
product: 'Chair',
manufacturer: 'IKEA'
},
{
product: 'Desk',
manufacturer: 'IKEA'
},
{
product: 'Chair',
manufacturer: 'Herman Miller'
}
]);
const grouped = collection.groupBy(function (item, key) {
return item.manufacturer.substring(0, 3);
});
grouped.all();
//=> {
//=> IKE: [
//=> {
//=> id: 100,
//=> product: 'Chair',
//=> manufacturer: 'IKEA',
//=> price: '1490 NOK'
//=> },
//=> {
//=> id: 150,
//=> product: 'Desk',
//=> manufacturer: 'IKEA',
//=> price: '900 NOK'
//=> }
//=> ],
//=> Her: [
//=> {
//=> id: 200,
//=> product: 'Chair',
//=> manufacturer: 'Herman Miller',
//=> price: '9990 NOK'
//=> }
//=> ]
//=> }
The has method determines if a given key exists in the collection:
const collection = collect({
animal: 'unicorn',
ability: 'magical'
});
collection.has('ability');
//=> true
An array of objects also works:
const collection = collect([{
animal: 'unicorn',
ability: 'magical'
}, {
anmial: 'pig',
ability: 'filthy'
}]);
collection.has('ability');
//=> true
The implode method joins the 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:
const collection = collect([{
product: 'Chair',
manufacturer: 'IKEA',
}, {
product: 'Desk',
manufacturer: 'IKEA',
}, {
product: 'Chair',
manufacturer: 'Herman Miller',
}]);
collection.implode('product', ',');
//=> Chair, Desk, Chair
If the collection contains simple strings or numeric values, simply pass the "glue" as the only argument to the method:
collect([1, 2, 3, 4, 5]).implode('-');
//=> 1-2-3-4-5
The intersect method removes any values from the original collection that are not present in the given array
or collection
. The resulting collection will preserve the original collection's keys:
const collection = collect([1, 2, 3, 4, 5]);
intersect = collection.intersect([1, 2, 3, 9]);
intersect.all();
//=> [1, 2, 3]
const firstCollection = collect([1, 2, 3, 4, 5]);
const secondCollection = collect([1, 2, 3, 9]);
intersect = firstCollection.intersect(secondCollection);
intersect.all();
//=> [1, 2, 3]
The isEmpty method returns true if the collection is empty; otherwise, false is returned:
collect([]).isEmpty();
//=> true
The isNotEmpty method returns true if the collection is not empty; otherwise, false is returned:
collect([1, 2, 3]).isNotEmpty();
//=> true
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:
const collection = collect([
{
product: 'Chair',
manufacturer: 'IKEA'
}, {
product: 'Desk',
manufacturer: 'IKEA'
}, {
product: 'Chair',
manufacturer: 'Herman Miller'
}
]);
const keyed = collection.keyBy('manufacturer');
keyed.all();
//=> {
//=> IKEA: {
//=> product: 'Desk',
//=> manufacturer: 'IKEA'
//=> },
//=> 'Herman Miller': {
//=> product: 'Chair',
//=> manufacturer: 'Herman Miller'
//=> }
//=> }
You may also pass a callback to the method. The callback should return the value to key the collection by:
const keyedUpperCase = collection.keyBy(function (item) {
return item['manufacturer'].toUpperCase();
});
keyedUpperCase.all();
//=> {
//=> IKEA: {
//=> product: 'Desk',
//=> manufacturer: 'IKEA'
//=> },
//=> 'HERMAN MILLER': {
//=> product: 'Chair',
//=> manufacturer: 'Herman Miller'
//=> }
//=> }
The keys method returns all of the collection's keys:
const collection = collect([{
name: 'Steven Gerrard',
number: 8
}, {
club: 'Liverpool',
nickname: 'The Reds'
}]);
keys = collection.keys();
//=> ['name', 'number', 'club', 'nickname']
The last method returns the last element in the collection that passes a given truth test:
const collection = collect([1, 2, 3]);
const last = collection.last(function (item) {
return item > 1;
});
//=> 3
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:
collect([1, 2, 3, 4]).last();
//=> 4
The map method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items:
const collection = collect([1, 2, 3, 4, 5]);
const multiplied = collection.map(function (item) {
return item * 2;
});
multiplied.all();
//=> [2, 4, 6, 8, 10]
Like most other collection methods,
map
returns a new collection instance; it does not modify the collection it is called on. If you want to transform the original collection, use thetransform
method.
The mapWithKeys method iterates through the collection and passes each value to the given callback. The callback should return an array where the first element represents the key and the second element represents the value pair:
const collection = collect([{
'name': 'John',
'department': 'Sales',
'email': '[email protected]'
}, {
'name': 'Jane',
'department': 'Marketing',
'email': '[email protected]'
}]);
const keyed = collection.mapWithKeys(function (item) {
return [item.email, item.name];
});
keyed.all();
//=> {
//=> '[email protected]': 'John',
//=> '[email protected]': 'Jane',
//=> }
The max method returns the maximum value of a given key:
const collection = collect([{
value: 10
}, {
value: -13
}, {
value: 12
}, {
unicorn: false
}]);
const max = collection.max('value');
//=> 12
collect([-1, -2345, 12, 11, 3]).max();
//=> 12
The median method returns the median value of a given key:
collect([1, 3, 3, 6, 7, 8, 9]).median();
//=> 6
collect([{
foo: 1
}, {
foo: 1
}, {
foo: 2
}, {
foo: 4
}]).median('foo');
//=> 1.5
The merge method merges the given object into the original collection. If a key in the given object matches a key in the original collection, the given objects value will overwrite the value in the original collection:
const collection = collect({
id: 1,
price: 29
});
const merged = collection.merge({
price: 400,
discount: false
});
merged.all();
//=> {id: 1, price: 400, discount: false}
If our collection is an array, the values will be appended to the end of the collection:
const collection = collect(['Unicorn', 'Rainbow']);
const merged = collection.merge(['Sunshine', 'Rainbow']);
merged.all();
//=> ['Unicorn', 'Rainbow', 'Sunshine', 'Rainbow']
The min method returns the minimum value of a given key:
const collection = collect[{
worth: 100
}, {
worth: 900
}, {
worth: 79
}]);
collection.min('worth');
//=> 79
collect([1, 2, 3, 4, 5]).min();
//=> 1
The mode method returns the mode value of a given key:
collect([1, 3, 3, 6, 7, 8, 9]).mode();
//=> [3]
collect([{
foo: 1
}, {
foo: 1
}, {
foo: 2
}, {
foo: 4
}]).mode('foo');
//=> [1]
The nth method creates a new collection consisting of every n-th element:
const collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);
const nth = collection.nth(4);
nth.all();
//=> ['a', 'e']
The only method returns the items in the collection with the specified keys:
const collection = collect({
id: 12,
name: 'John Doe',
email: '[email protected]'
active: true
});
const filtered = collection.only(['name', 'email']);
//=> {name: 'John Doe', email: '[email protected]'}
For the inverse of
only
, see theexcept
method.
The partition method may be combined with destructuring to separate elements that pass a given truth test from those that do not:
const collection = collect([1, 2, 3, 4, 5, 6]);
const [underThree, underThree] = collection.partition(function (i) {
return i < 3;
});
The pipe method passes the collection to the given callback and returns the result:
const collection = collect([1, 2, 3]);
const piped = collection.pipe(function (collection) {
return collection.sum();
});
//=> 6
The pluck method retrieves all of the values for a given key:
const collection = collect([{
id: 78,
name: 'Aeron'
}, {
id: 79,
name: 'Embody'
}]);
const plucked = collection.pluck('name');
plucked.all();
//=> ['Aeron', 'Embody']
You may also specify how you wish the resulting collection to be keyed:
const collection = collect([{
id: 78,
name: 'Aeron'
}, {
id: 79,
name: 'Embody'
}]);
const plucked = collection.pluck('name', 'id');
plucked.all();
//=> {
//=> 78: 'Aeron',
//=> 79: 'Embody'
//=> }
The pop method removes and returns the last item from the collection:
const collection = collect([1, 2, 3, 4, 5]);
collection.pop();
//=> 5
collection.all();
// => [1, 2, 3, 4]
The prepend method adds an item to the beginning of the collection:
const collection = collect([1, 2, 3, 4, 5]);
collection.prepend(0);
collection.all();
//=> [0, 1, 2, 3, 4, 5]
You may also pass a second argument to set the key of the prepended item:
Pro tip: Order of properties in objects is not guaranteed in JavaScript; When calling prepend with a key, the Collection uses the underlying
put
method behind the scenes. This is only supported so that collect.js have the same api as Laravel Collections.
const collection = collect({
product: 'iPhone 6s'
});
collection.prepend('Apple', 'brand');
collection.all():
//=> {
//=> brand: 'Apple',
//=> product: 'iPhone 6s'
//=> }
The pull method removes and returns an item from the collection by its key:
const collection = collect({
firstname: 'Michael',
lastname: 'Cera'
});
collection.pull('lastname');
//=> Cera
collection.all();
//=> {firstname: 'Michael'}
The push method appends an item to the end of the collection:
const collection = collect([1, 2, 3, 4]);
collection.push(5);
collection.all();
//=> [1, 2, 3, 4, 5]
The put method sets the given key and value in the collection:
const collection = collect(['JavaScript', 'Python']);
collection.put('Ruby');
collection.all();
//=> ['JavaScript', 'Python', 'Ruby']
The random method returns a random item from the collection:
const collection = collect([1, 2, 3, 4, 5]);
collection.random();
//=> 4 (retrieved randomly)
You may optionally pass an integer to random to specify how many items you would like to randomly retrieve. If that integer is more than 1, a collection of items is returned:
const random = collection.random(3);
//=> [5, 3, 4] (retrieved randomly)
The reduce method reduces the collection to a single value, passing the result of each iteration into the subsequent iteration:
const collection = collect([1, 2, 3]);
const total = collection.reduce(function (carry, item) {
return carry + item;
});
//=> 6
The value for carry
on the first iteration is null; however, you may specify its initial value by passing a second argument to reduce:
const total = collection.reduce(function (carry, item) {
return carry + item;
}, 4);
//=> 10
The reject method filters the collection using the given callback. The callback should return true if the item should be removed from the resulting collection:
const collection = collect([1, 2, 3, 4]);
const filtered = collection.reject(function (value) {
return value > 2;
});
//=> [1, 2]
For the inverse of the
reject
method, see thefilter
method.
The reverse method reverses the order of the collection's items:
const collection = collect([1, 2, 3, 4, 5]);
const reversed = collection.reverse();
reversed.all();
//=> [5, 4, 3, 2, 1]
The search method searches the collection for the given value and returns its key if found. If the item is not found, false is returned.
const collection = collect([2, 4, 6, 8]);
collection.search(4);
//=> 1
The search is done using a "loose" comparison, meaning a string with an integer value will be considered equal to an integer of the same value. To use strict comparison, pass true as the second argument to the method:
collection.search('4', true);
//=> false
Alternatively, you may pass in your own callback to search for the first item that passes your truth test:
collection.search(function (item, key) {
return item > 5;
});
//=> 2
The shift method removes and returns the first item from the collection:
const collection = collect([1, 2, 3, 4, 5]);
collection.shift();
//=> 1
collection.all();
//=> [2, 3, 4, 5]
The shuffle method randomly shuffles the items in the collection:
const collection = collect([1, 2, 3, 4, 5]);
const shuffled = collection.shuffle();
shuffled.all();
//=> [3, 5, 1, 2, 4] (generated randomly)
The slice method returns a slice of the collection starting at the given index:
const collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
const slice = collection.slice(4);
slice.all();
//=> [5, 6, 7, 8, 9, 10]
If you would like to limit the size of the returned slice, pass the desired size as the second argument to the method:
const slice = collection.slice(4, 2);
slice.all();
//=> [5, 6]
The sort method sorts the collection:
const collection = collect([5, 3, 1, 2, 4]);
const sorted = collection.sort();
sorted.all();
//=> [1, 2, 3, 4, 5]
If your sorting needs are more advanced, you may pass a callback to sort with your own algorithm.
const collection = collect([5, 3, 1, 2, 4]);
const sorted = collection.sort(function (a, b) {
return b - a;
});
sorted.all();
//=> [5, 4, 3, 2, 1]
If you need to sort a collection of nested arrays or objects, see the
sortBy
andsortByDesc
methods.
The sortBy method sorts the collection by the given key. The sorted collection keeps the original array keys, so in this example we'll use the values method to reset the keys to consecutively numbered indexes:
const collection = collect([
{name: 'Desk', price: 200},
{name: 'Chair', price: 100},
{name: 'Bookcase', price: 150},
]);
const sorted = collection.sortBy('price');
sorted.all();
//=> [
//=> {name: 'Chair', price: 100},
//=> {name: 'Bookcase', price: 150},
//=> {name: 'Desk', price: 200},
//=> ]
You can also pass your own callback to determine how to sort the collection values:
const collection = collect([
{name: 'Desk', colors: ['Black', 'Mahogany']},
{name: 'Chair', colors: ['Black']},
{name: 'Bookcase', colors: ['Red', 'Beige', 'Brown']},
]);
const sorted = collection.sortBy(function (product, key) {
return product['colors'].length;
});
sorted.all();
//=> [
//=> {name: 'Chair', colors: ['Black']},
//=> {name: 'Desk', colors: ['Black', 'Mahogany']},
//=> {name: 'Bookcase', colors: ['Red', 'Beige', 'Brown']},
//=> ]
This method has the same signature as the sortBy
method, but will sort the collection in the opposite order.
The splice method removes and returns a slice of items starting at the specified index:
const collection = collect([1, 2, 3, 4, 5]);
const chunk = collection.splice(2);
chunk.all();
//=> [3, 4, 5]
collection.all();
//=> [1, 2]
You may pass a second argument to limit the size of the resulting chunk:
const collection = collect([1, 2, 3, 4, 5]);
const chunk = collection.splice(2, 1);
chunk.all();
//=> [3]
collection.all();
//=> [1, 2, 4, 5]
The split method breaks a collection into the given number of groups:
const collection = collect([1, 2, 3, 4, 5]);
const groups = collection.split(3);
//=> [[1, 2], [3, 4], [5]]
In addition, you can pass a third argument containing the new items to replace the items removed from the collection:
const collection = collect([1, 2, 3, 4, 5]);
const chunk = collection.splice(2, 1, [10, 11]);
chunk.all()
//=> [3]
collection.all();
//=> [1, 2, 10, 11, 4, 5]
The sum method returns the sum of all items in the collection:
collect([1, 2, 3]).sum();
//=> 6
If the collection contains nested arrays or objects, you should pass a key to use for determining which values to sum:
const collection = collect([
{name: 'JavaScript: The Good Parts', pages: 176},
{name: 'JavaScript: The Definitive Guide', pages: 1096},
]);
collection.sum('pages');
//=> 1272
In addition, you may pass your own callback to determine which values of the collection to sum:
const collection = collect([
{name: 'Desk', colors: ['Black', 'Mahogany']},
{name: 'Chair', colors: ['Black']},
{name: 'Bookcase', colors: ['Red', 'Beige', 'Brown']},
]);
const total = collection.sum(function (product) {
return product.colors.length;
});
//=> 6
The take method returns a new collection with the specified number of items: You may also pass a negative integer to take the specified amount of items from the end of the collection:
const collection = collect([0, 1, 2, 3, 4, 5]);
const chunk = collection.take(3);
chunk.all();
//=> [0, 1, 2]
The tap method passes the collection to the given callback, allowing you to "tap" into the collection at a specific point and do something with the items while not affecting the collection itself:
const collect([2, 4, 3, 1, 5])
.sort()
.tap(function (collection) {
console.log(collection.all());
//=> [1, 2, 3, 4, 5]
})
.shift();
//=> 1
The times method creates a new collection by invoking the callback a given amount of times:
const collection = collect().times(10, function (number) {
return number * 9;
});
collection.all();
//=> [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]
Use
all
instead oftoArray
The toJson method converts the collection into JSON string:
const collection = collect({
id: 384,
name: 'Rayquaza',
gender: 'NA'
});
const json = collection.toJson();
//=> {"id": 384, "name": "Rayquaza", "gender": "NA"}
The transform method iterates over the collection and calls the given callback with each item in the collection. The items in the collection will be replaced by the values returned by the callback:
const collection = collect([1, 2, 3, 4, 5]);
collection.transform(function (item, key) {
return item * 2;
});
collection.all();
//=> [2, 4, 6, 8, 10]
Unlike most other collection methods,
transform
modifies the collection itself. If you wish to create a new collection instead, use themap
method.
The union method adds the given array to the collection. If the given array contains keys that are already in the original collection, the original collection's values will be preferred:
const collection = collect({
a: 'A',
b: 'B'
});
const union = collection.union({
a: 'AAA',
c: 'CCC',
b: 'BBB'
});
union.all();
//=> {
//=> a: 'A',
//=> b: 'B',
//=> c: 'CCC'
//=> }
The unique method returns all of the unique items in the collection:
const collection = collect([1, 1, 1, 2, 3, 3]);
const unique = collection.unique();
unique.all();
//=> [1, 2, 3]
When dealing with an array of objects, you may specify the key used to determine uniqueness:
const collection = collect([
{name: 'iPhone 6', brand: 'Apple', type: 'phone'},
{name: 'iPhone 5', brand: 'Apple', type: 'phone'},
{name: 'Apple Watch', brand: 'Apple', type: 'watch'},
{name: 'Galaxy S6', brand: 'Samsung', type: 'phone'},
{name: 'Galaxy Gear', brand: 'Samsung', type: 'watch'}
]);
const unique = collection.unique('brand');
unique.all();
//=> [
//=> {name: 'iPhone 6', brand: 'Apple', type: 'phone'},
//=> {name: 'Galaxy S6', brand: 'Samsung', type: 'phone'},
//=> ]
You may also pass your own callback to determine item uniqueness:
const collection = collect([
{name: 'iPhone 6', brand: 'Apple', type: 'phone'},
{name: 'iPhone 5', brand: 'Apple', type: 'phone'},
{name: 'Apple Watch', brand: 'Apple', type: 'watch'},
{name: 'Galaxy S6', brand: 'Samsung', type: 'phone'},
{name: 'Galaxy Gear', brand: 'Samsung', type: 'watch'}
]);
const unique = collection.unique(function (item) {
return item.brand + item.type;
});
unique.all();
//=> [
//=> {name: 'iPhone 6', brand: 'Apple', type: 'phone'},
//=> {name: 'Apple Watch', brand: 'Apple', type: 'watch'},
//=> {name: 'Galaxy S6', brand: 'Samsung', type: 'phone'},
//=> {name: 'Galaxy Gear', brand: 'Samsung', type: 'watch'},
//=> ]
The values method returns a new collection with the keys reset to consecutive integers:
const collection = collect({a: 'xoxo', b: 'abab', 'c': '1337', 1337: 12});
const values = collection.values();
values.all();
//=> [12, 'xoxo', 'abab', '1337']
The when method will execute the given callback when the first argument given to the method evaluates to true:
const collection = collect([1, 2, 3]);
collection.when(true, function (collection) {
return collection.push(4);
});
collection.all();
// [1, 2, 3, 4]
The where method filters the collection by a given key / value pair:
const collection = collect([
{'product': 'Desk', 'price': 200},
{'product': 'Chair', 'price': 100},
{'product': 'Bookcase', 'price': 150},
{'product': 'Door', 'price': '100'},
]);
const filtered = collection.where('price', 100);
filtered.all();
//=> [
//=> {'product': 'Chair', 'price': 100},
//=> {'product': 'Door', 'price': '100'}
//=> ]
The where method also allows for custom comparisons:
Non-identity / strict inequality (!==)
const filtered = collection.where('price', '!==', 100);
filtered.all();
//=> [
//=> {'product': 'Desk', 'price': 200},
//=> {'product': 'Bookcase', 'price': 150},
//=> {'product': 'Door', 'price': '100'},
//=> ]
Less than operator (<)
const filtered = collection.where('price', '<', 100);
filtered.all();
//=> []
This method has the same signature as the where
method; however, all values are compared using "strict" comparisons.
The whereIn method filters the collection by a given key / value contained within the given array.
const collection = collect([
{product: 'Desk', price: 200},
{product: 'Chair', price: 100},
{product: 'Bookcase', price: 150},
{product: 'Door', price: 100},
]);
const filtered = collection.whereIn('price', [100, 150]);
filtered.all();
//=> [
//=> {product: 'Chair', price: 100},
//=> {product: 'Bookcase', price: 150},
//=> {product: 'Door', price: 100},
//=> ]
The
whereIn
method uses strict comparisons when checking item values. Use thewhereInLoose
method to filter using "loose" comparisons.
This method has the same signature as the whereIn
method; however, all values are compared using "loose" comparisons.
The whereNotIn method filters the collection by a given key / value not contained within the given array:
const collection = collect([
{ product: 'Desk', price: 200 },
{ product: 'Chair', price: 100 },
{ product: 'Bookcase', price: 150 },
{ product: 'Door', price: 100 }
]);
const filtered = collection.whereNotIn('price', [150, 200]);
filtered.all();
//=> [
//=> { product: 'Chair', price: 100 },
//=> { product: 'Door', price: 100 }
//=> ]
The zip method merges together the values of the given array with the values of the original collection at the corresponding index:
const collection = collect(['Chair', 'Desk']);
const zipped = collection.zip([100, 200]);
zipped.all();
//=> [['Chair', 100], ['Desk', 200]]
PRs are welcomed to this project, and help is needed in order to keep up with the changes of Laravel Collections. If you want to improve the collection library, add functionality or improve the docs please feel free to submit a PR.
MIT © Daniel Eckermann