Collect.js
is the javascript library for collecting data from tree-based structures. This library is used on JavaScript Array and Objects. Collect.js
framework that allows merchants to collect sensitive payment information from their customers without exposing their website to sensitive information. 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. npm install collect.js --save
yarn add collect.js
<script>
collect.min.js
<script>
collect([1, 2, 3]).all();
// [1, 2, 3]
collect({
firstname: 'Darwin',
lastname: 'Núñez',
}).all();
// {
// firstname: 'Darwin',
// lastname: 'Núñez',
// }
average()
method is used to return the average of all the items in a collection. This method is an alias of avg()
method.collect(array).average()
collect()
method takes one argument that is converted into the collection and then average()
function is applied on it, which can take element if you apply it on the collection of objects.const collect = require('collect.js');
let arr = [10, 20, 30];
let average = collect(arr).average();
console.log("Average of the given array: ", average);
Average of the given array: 20
avg()
method returns the average of all the items in a collection.collect()
takes one argument that is converted into the collection and then avg()
function is applied on it, which can take element if you apply it on the collection of objects.avg()
method example :const collect = require('collect.js');
let arr = [
{
name: 'Ramana',
score: 98,
},
{
name: 'Venkat',
score: 96,
},
{
name: 'Suresh',
score: 80
},
];
// converting object to collection
const collection = collect(arr);
// finding the average of all the score
let averageScore = collection.avg('score');
console.log("Average score of students : ", averageScore);
Average score of students : 91.33333333333
chunk() method
breaks the collection into multiple, smaller collections of a given size :data.chunk(x)
Example :
const collect = require('collect.js');
const collection = collect([1, 2, 3, 4, 5, 6, 7]);
const x = collection.chunk(5);
console.log(x.all());
Output :
[ Collection { items: [ 1, 2, 3, 4, 5 ] },
Collection { items: [ 6, 7 ] } ]
collapse()
: 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]
combine()
: 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(['Free Time Learn', 12]);
combine.all();
// {
// name: 'Free Time Learn',
// number: 12
// }
concat()
: The concat() method is used to merge two or more collections/arrays/objects :concat()
an array of objects, or a multidimensional arrayconst collection = collect([1, 2, 3]);
let concatenated = collection.concat(['a', 'b', 'c']);
concatenated = concatenated.concat({
name: 'Free Time Learning',
number: 12,
});
concatenated.all();
// [1, 2, 3, 'a', 'b', 'c', 'Free Time Learn', 12]
contains()
: The contains() method determines whether the collection contains a given item :const collection = collect({
name: 'Free Time Learn',
number: 12,
});
collection.contains('name');
// true
collection.contains('age');
// false
collection.contains('Free Time Learn');
// true
const collection = collect([1, 2, 3]);
collection.contains(3);
// true
const collection = collect({
name: 'Free Time Learn',
number: 12,
});
collection.contains('name', 'Steve Jobs');
// false
const collection = collect([1, 2, 3, 4, 5]);
collection.contains((value, key) => value > 5);
// false
containsOneItem()
: The containsOneItem() method returns true if the collection contains exactly one item; otherwise, false is returned.collect([1]).containsOneItem();
// true
collect({ firstname: 'Luis' }).containsOneItem();
// true
collect('value').containsOneItem();
// true
collect([1, 2, 3]).containsOneItem();
// false
collect({ firstname: 'Luis', lastname: 'Díaz' }).containsOneItem();
// false
collect().containsOneItem();
// false
collect([]).containsOneItem();
// false
collect({}).containsOneItem();
// false
count()
: The count() method returns the total number of items in the collection.const collection = collect([1, 2, 3, 4]);
collection.count();
// 4
countBy()
: The countBy() method counts the occurences of values in the collection. By default, the method counts the occurrences of every element:const collection = collect([1, 2, 2, 2, 3]);
const counted = collection.countBy();
counted.all();
// {
// 1: 1,
// 2: 3,
// 3: 1,
// }
const collection = collect([
'freetimelearn@gmail.com',
'info@freetimelearning.com',
'vvramanareddy9963@gmail.com',
]);
const counted = collection.countBy(email => email.split('@')[1]);
counted.all();
// {
// 'gmail.com': 2,
// 'freetimelearning.com': 1,
// }
crossJoin()
: The crossJoin() method cross joins the collection with the given array or collection, returning all possible permutations:const collection = collect([1, 2]);
const joined = collection.crossJoin(['a', 'b']);
joined.all();
// [
// [1, 'a'],
// [1, 'b'],
// [2, 'a'],
// [2, 'b'],
// ]
dd()
: The dd() method will console.log the collection and exit the current process:const collection = collect([1, 2, 3]).dd();
// Collection { items: [ 1, 2, 3 ] }
// (Exits node.js process)
diff()
: 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]
diffAssoc()
: The diffAssoc() method compares the collection against another collection or a plain object based on its keys and values. This method will return the key / value pairs in the original collection that are not present in the given collection:const collection = collect({
color: 'orange',
type: 'fruit',
remain: 6,
});
const diff = collection.diffAssoc({
color: 'yellow',
type: 'fruit',
remain: 3,
used: 6,
});
diff.all();
// { color: 'orange', remain: 6 };
diffKeys()
: 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' }
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:const collection = collect([1, 2, 3, 4, 5]);
collection.doesntContain(value => value < 5);
// false
const collection = collect([1, 2, 3]);
collection.doesntContain(4);
// true
const collection = collect({
name: 'Free Time Learn',
number: 12,
});
collection.doesntContain('Free Time Learn');
// false
collection.doesntContain('Darwin Núñez');
// true
const collection = collect({
name: 'Free Time Learn',
number: 11,
});
collection.doesntContain('name', 'Darwin Núñez');
// true
dump()
: The dump() method outputs the results at that moment and then continues processing:collect([1, 2, 3, 4])
.dump()
.map(item => item * 2)
.dump();
// Collection { items: [ 1, 2, 3, 4 ] }
// Collection { items: [ 2, 4, 6, 8 ] }
duplicates()
: The duplicates() method retrieves and returns duplicate values from the collection:const collection = collect(['a', 'b', 'a', 'c', 'b']);
const duplicates = collection.duplicates();
duplicates.all();
// { 2: 'a', 4: 'b' }
each()
: 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((item) => {
sum += item;
});
// console.log(sum);
// 14
let sum = 0;
const collection = collect([1, 3, 3, 7]);
collection.each((item) => {
sum += item;
if (sum > 5) {
return false;
}
});
// console.log(sum);
// 7
eachSpread()
: The eachSpread() method iterates over the collection's items, passing each nested item value into the given callback:const collection = collect([['John Doe', 35], ['Jane Doe', 33]]);
collection.eachSpread((name, age) => {
//
});
You may stop iterating through the items by returning false from the callback:
collection.eachSpread((name, age) => false);
every()
: 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((value, key) => value > 2);
// false
except()
: 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 }
collect([1, 2, 3, 4])
.except([2, 12])
.all();
// [1, 3, 4]
except
, see the only
method.filter()
: 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((value, key) => value > 2);
filtered.all();
// [3, 4]
false
will be removed :const collection = collect([
0,
1,
2,
null,
3,
4,
undefined,
5,
6,
7,
[],
8,
9,
{},
10,
]);
const filtered = collection.filter();
filtered.all();
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filter
, see the reject
method.reject()
: 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(value => value > 2);
// [1, 2]
reject
method, see the filter
method.first()
: The first() method returns the first element in the collection that passes a given truth test:collect([1, 2, 3, 4]).first(item => item > 1);
// 2
collect([1, 2, 3, 4]).first();
// 1
firstOrFail()
: The firstOrFail() method returns the first element in the collection, or throws an error if there are no elements:collect([1, 2, 3, 4]).firstOrFail(item => item > 1);
// 2
collect([1, 2, 3, 4]).firstOrFail(item => item > 4);
// Error ('Item not found.') is thrown.
collect([1, 2, 3, 4]).firstOrFail();
// 1
collect().firstOrFail();
// Error ('Item not found.') is thrown.
const collection = collect([
{ product: 'Desk', price: 200, discounted: true },
{ product: 'Chair', price: 100, discounted: true },
{ product: 'Bookcase', price: 150, discounted: true },
{ product: 'Door', price: 100 },
]);
collection.firstOrFail('product', '=', 'Desk');
// { product: 'Desk', price: 200, discounted: true }
firstWhere()
: The firstWhere() method returns the first element in the collection with the given key / value pair:const collection = collect([
{ name: 'Regena', age: 12 },
{ name: 'Linda', age: 14 },
{ name: 'Diego', age: 23 },
{ name: 'Linda', age: 84 },
]);
collection.firstWhere('name', 'Linda');
// { name: 'Linda', age: 14 }
flatMap()
: 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: 'Ramana Reddy',
number: 27,
},
{
name: 'Free Time Learn',
number: 11,
},
]);
const flatMapped = collection.flatMap(value => value.name.toUpperCase());
flatMapped.all();
// ['RAMANA REDDY', 'FREE TIME LEARN']
flatten()
: The flatten() method flattens a multi-dimensional collection into a single dimension:const collection = collect({
club: 'Liverpool',
players: ['Salah', 'Firmino', 'Núñez'],
});
const flattened = collection.flatten();
flattened.all();
// ['Liverpool', 'Salah', 'Firmino', 'Núñez'];
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' },
// ]
iPhone 6S
', 'Apple
', 'Galaxy S7
', 'Samsung
']. Providing a depth allows you to restrict the levels of nested arrays that will be flattened.flip()
: The flip() method swaps the collection's keys with their corresponding values:const collection = collect({
name: 'Free Time Learn',
number: 31,
});
const flipped = collection.flip();
flipped.all();
// {
// 'Free Time Learn': 'name',
// '31': 'number',
// }
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:const collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
const forPage = collection.forPage(2, 3);
forPage.all();
// [4, 5, 6]
get()
: The get() method returns the item at a given key or index. If the key or index does not exist, null is returned:const collection = collect({
firstname: 'Mohamed',
lastname: 'Salah',
});
collection.get('lastname');
// Salah
collection.get('middlename');
// null
const collection = collect(['a', 'b', 'c']);
collection.get(1);
// b
const collection = collect({
firstname: 'Mohamed',
lastname: 'Salah',
});
collection.get('middlename', 'default-value');
// default-value
const collection = collect({
firstname: 'Mohamed',
lastname: 'Salah',
});
collection.get('middlename', () => 'default-value');
// default-value
forget()
: The forget() method removes an item from the collection by its key:const collection = collect({
name: 'Darwin Núñez',
number: 27,
});
collection.forget('number');
collection.all();
// {
// name: 'Darwin Núñez',
// }
groupBy()
: The groupBy() method groups the collection's items into multiple collections 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: Collection {
// items: [
// {
// id: 100,
// product: 'Chair',
// manufacturer: 'IKEA',
// price: '1490 NOK',
// },
// {
// id: 150,
// product: 'Desk',
// manufacturer: 'IKEA',
// price: '900 NOK',
// },
// ],
// },
// 'Herman Miller': Collection {
// items: [
// {
// id: 200,
// product: 'Chair',
// manufacturer: 'Herman Miller',
// price: '9990 NOK',
// },
// ],
// },
// }
const collection = collect([
{
product: 'Chair',
manufacturer: 'IKEA',
},
{
product: 'Desk',
manufacturer: 'IKEA',
},
{
product: 'Chair',
manufacturer: 'Herman Miller',
},
]);
const grouped = collection.groupBy((item, key) => item.manufacturer.substring(0, 3));
grouped.all();
// {
// IKE: Collection {
// items: [
// {
// id: 100,
// product: 'Chair',
// manufacturer: 'IKEA',
// price: '1490 NOK',
// },
// {
// id: 150,
// product: 'Desk',
// manufacturer: 'IKEA',
// price: '900 NOK',
// },
// ],
// },
// Her: Collection {
// items: [
// {
// id: 200,
// product: 'Chair',
// manufacturer: 'Herman Miller',
// price: '9990 NOK',
// },
// ],
// },
// }
implode()
: 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
collect([1, 2, 3, 4, 5]).implode('-');
// 1-2-3-4-5
intersect()
: 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]
intersectByKeys()
: The intersectByKeys() method removes any keys from the original collection that are not present in the given array or collection:const collection = collect({
serial: 'UX301',
type: 'screen',
year: 2009,
});
const intersect = collection.intersectByKeys({
reference: 'UX404',
type: 'tab',
year: 2011,
});
intersect.all();
// { type: 'screen', year: 2009 }
const firstCollection = collect([1, 2, 3, 4, 5]);
const secondCollection = collect([1, 2, 3, 9]);
intersect = firstCollection.intersect(secondCollection);
intersect.all();
// [1, 2, 3]
isEmpty()
: The isEmpty method returns true if the collection is empty;
otherwise, false is returned:collect().isEmpty();
// true
collect([]).isEmpty();
// true
collect({}).isEmpty();
// true
isNotEmpty()
: The isNotEmpty() method returns true if the collection is not empty;
otherwise, false is returned:collect([1, 2, 3]).isNotEmpty();
// true
collect().isNotEmpty();
// false
collect([]).isNotEmpty();
// false
collect({}).isNotEmpty();
// false
join()
: The join() method joins the collection's values with a string:collect(['a', 'b', 'c']).join(', ');
// 'a, b, c'
collect(['a', 'b', 'c']).join(', ', ', and ');
// 'a, b, and c'
collect(['a', 'b']).join(', ', ' and ');
// 'a and b'
collect(['a']).join(', ', ' and ');
// 'a'
collect([]).join(', ', ' and ');
// ''
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: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',
// },
// }
const upperCased = collection.keyBy(item => item.manufacturer.toUpperCase());
upperCased.all();
// {
// IKEA: {
// product: 'Desk',
// manufacturer: 'IKEA',
// },
// 'HERMAN MILLER': {
// product: 'Chair',
// manufacturer: 'Herman Miller',
// },
// }
keys()
: The keys() method returns all of the collection's keys:const collection = collect([
{
club: 'Liverpool',
nickname: 'The Reds',
},
]);
keys = collection.keys();
// ['club', 'nickname']
last()
: 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(item => item > 1);
// 3
collect([1, 2, 3, 4]).last();
// 4
macro()
: The macro() method lets you register custom methodscollect().macro('uppercase', function () {
return this.map(item => item.toUpperCase());
});
const collection = collect(['a', 'b', 'c']);
collection.uppercase();
collection.all();
// ['A', 'B', 'C']
make()
: The make() method creates a new collection instance.Collect.js
it's recommended to use collect()
directly when creating a new collection.map()
: 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(item => item * 2);
multiplied.all();
// [2, 4, 6, 8, 10]
mapInto()
: The mapInto() method iterates through the collection and instantiates the given class with each element as a constructor:const Player = function (name) {
this.name = name;
};
const collection = collect([
'Roberto Firmino',
'Darwin Núñez',
]);
const players = collection.mapInto(Player);
players.all();
// [
// Player { name: 'Roberto Firmino' },
// Player { name: 'Darwin Núñez' },
// ]
mapSpread()
: The mapSpread() method iterates over the collection's items, passing each nested item value into 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([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const chunks = collection.chunk(2);
const sequence = chunks.mapSpread((even, odd) => even + odd);
sequence.all();
// [1, 5, 9, 13, 17]
mapToDictionary()
: Run a dictionary map over the items. The callback should return an associative array with a single key/value pair.const collection = collect([
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
{ id: 3, name: 'c' },
{ id: 4, name: 'b' },
]);
const groups = collection.mapToDictionary(item => [item.name, item.id]);
groups.all();
// {
// a: [1],
// b: [2, 4],
// c: [3],
// }
mapToGroups()
: The mapToGroups() method iterates through the collection and passes each value to the given callback:const collection = collect([
{ id: 1, name: 'A' },
{ id: 2, name: 'B' },
{ id: 3, name: 'C' },
{ id: 4, name: 'B' },
]);
const groups = collection.mapToGroups((item, key) => [item.name, item.id]);
// {
// A: [1],
// B: [2, 4],
// C: [3],
// }
mapWithKeys()
: 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: 'john@example.com',
},
{
name: 'Jane',
department: 'Marketing',
email: 'jane@example.com',
},
]);
const keyed = collection.mapWithKeys(item => [item.email, item.name]);
keyed.all();
// {
// 'john@example.com': 'John',
// 'jane@example.com': 'Jane',
// }
max()
: 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
merge()
: 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 }
const collection = collect(['Unicorn', 'Rainbow']);
const merged = collection.merge(['Sunshine', 'Rainbow']);
merged.all();
// ['Unicorn', 'Rainbow', 'Sunshine', 'Rainbow']
mergeRecursive()
: The mergeRecursive() method merges the given array or collection recursively with the original collection. If a string key in the given items matches a string key in the original collection, then the values for these keys are merged together into an array, and this is done recursively:const collection = collect({
product_id: 1,
price: 100,
});
const merged = collection.mergeRecursive({
product_id: 2,
price: 200,
discount: false,
});
merged.all();
// {
// product_id: [1, 2],
// price: [100, 200],
// discount: false,
// }
min()
: 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
pad()
: The pad() method will fill the array with the given value until the array reaches the specified size. This method behaves like the array_pad PHP function.const collection = collect(['A', 'B', 'C']);
let filtered = collection.pad(5, 0);
filtered.all();
// ['A', 'B', 'C', 0, 0]
filtered = collection.pad(-5, 0);
filtered.all();
// [0, 0, 'A', 'B', 'C']
partition()
: 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, overThree] = collection.partition(i => i < 3);
pull()
: 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' }
push()
: 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]
put()
: 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']
random()
: The random() method returns a random item from the collection:const collection = collect([1, 2, 3, 4, 5]);
collection.random();
// 4 (retrieved randomly)
const threeRandom = collection.random(3);
// Collection { items: [ 5, 3, 4 ] } (retrieved randomly)
const oneRandom = collection.random(1);
// Collection { items: [ 3 ] } (retrieved randomly)
oneRandom.all();
// [3]
reduce()
: 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((carry, item) => 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((carry, item) => carry + item, 4);
// 10
replace()
: The replace() method behaves similarly to merge; however, in addition to overwriting matching items with string keys, the replace method will also overwrite items in the collection that have matching numeric keys:const collection = collect({
name: 'Bob',
});
const replaced = collection.replace({
name: 'John',
number: 45,
});
replaced.all();
// {
// name: 'John',
// number: 45,
// }
replaceRecursive()
: This method works like replace, but it will recurse into arrays and apply the same replacement process to the inner values:const collection = collect([
'Matip',
'van Dijk',
[
'Núñez',
'Firmino',
'Salah',
],
]);
const replaced = collection.replaceRecursive({
0: 'Gomez',
2: { 1: 'Origi' },
});
replaced.all();
// {
// 0: 'Gomez',
// 1: 'van Dijk',
// 2: { 0: 'Núñez', 1: 'Origi', 2: 'Salah' },
// }
search()
: 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
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((item, key) => item > 5);
// 2
shift()
: 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]
const collection = collect([1, 2, 3, 4, 5]);
collection.shift(2).all();
// [1, 2]
collection.all();
// => [3, 4, 5]
shuffle()
: 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)
skip()
: The skip() method returns a new collection, without the first given amount of items:const collection = collect([1, 2, 3, 4, 5, 6]);
collection.skip(4).all();
// [5, 6]
const collection = collect({
first: 'first',
second: 'second',
third: 'third',
fourth: 'fourth',
fifth: 'fifth',
});
collection.skip(4).all();
// { fifth: 'fifth' }
skipUntil()
: The skipUntil() method skips items until the given callback returns true and then returns the remaining items in the collection:const collection = collect([1, 2, 3, 4]);
const subset = collection.skipUntil(item => item >= 3);
subset.all();
// [3, 4]
const collection = collect([1, 2, 3, 4]);
const subset = collection.skipUntil(3);
subset.all();
// [3, 4]
skipWhile()
: The skipWhile() method
skips items while the given callback returns true and then returns the remaining items in the collection:const collection = collect([1, 2, 3, 4]);
const subset = collection.skipWhile(item => item <= 3);
subset.all();
// [4]
const collection = collect([1, 1, 2, 2, 3, 3, 4, 4]);
const subset = collection.skipWhile(1);
subset.all();
// [2, 2, 3, 3, 4, 4]
sort()
: 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]
const collection = collect([5, 3, 1, 2, 4]);
const sorted = collection.sort((a, b) => b - a);
sorted.all();
// [5, 4, 3, 2, 1]
sortBy()
: 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 },
// ]
const collection = collect([
{
name: 'Desk',
price: 200,
manufacturer: {
name: 'IKEA',
},
},
{
name: 'Chair',
price: 100,
manufacturer: {
name: 'Herman Miller',
},
},
{
name: 'Bookcase',
price: 150,
manufacturer: {
name: 'IKEA',
},
},
]);
const sorted = collection.sortBy('manufacturer.name');
sorted.all();
// [
// {
// name: 'Chair',
// price: 100,
// manufacturer: {
// name: 'Herman Miller',
// },
// },
// {
// name: 'Desk',
// price: 200,
// manufacturer: {
// name: 'IKEA',
// },
// },
// {
// name: 'Bookcase',
// price: 150,
// manufacturer: {
// name: 'IKEA',
// },
// },
// ]
const collection = collect([
{ name: 'Desk', colors: ['Black', 'Mahogany'] },
{ name: 'Chair', colors: ['Black'] },
{ name: 'Bookcase', colors: ['Red', 'Beige', 'Brown'] },
]);
const sorted = collection.sortBy((product, key) => product.colors.length);
sorted.all();
// [
// { name: 'Chair', colors: ['Black'] },
// { name: 'Desk', colors: ['Black', 'Mahogany'] },
// { name: 'Bookcase', colors: ['Red', 'Beige', 'Brown'] },
// ]
sortByDesc()
: This method has the same signature as the sortBy method, but will sort the collection in the opposite order.sortDesc()
: This method will sort the collection in the opposite order as the sort method.const collection = collect([1, 3, 5, 2, 4]);
const sorted = collection.sortDesc();
sorted.all();
// [5, 4, 3, 2, 1]
sortKeys()
: The sortKeys() method sorts the collection by the keys of the underlying associative array:const collection = collect({
id: 10,
first: 'Darwin',
last: 'Núñez',
});
const sorted = collection.sortKeys();
sorted.all();
// {
// first: 'Darwin',
// id: 10,
// last: 'Núñez',
// }
sortKeysDesc()
: This method has the same signature as the sortKeys method, but will sort the collection in the opposite order.sum()
: The sum() method returns the sum of all items in the collection :collect([1, 2, 3]).sum();
// 6
const collection = collect([
{ name: 'My story', pages: 176 },
{ name: 'Fantastic Beasts and Where to Find Them', pages: 1096 },
]);
collection.sum('pages');
// 1272
const collection = collect([
{ name: 'Desk', colors: ['Black', 'Mahogany'] },
{ name: 'Chair', colors: ['Black'] },
{ name: 'Bookcase', colors: ['Red', 'Beige', 'Brown'] },
]);
const total = collection.sum(product => product.colors.length);
// 6
take()
: 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]
takeUntil()
: The takeUntil() method returns items in the collection until the given callback returns true:const collection = collect([1, 2, 3, 4]);
const subset = collection.takeUntil(item => item >= 3);
subset.all();
// [1, 2]
const collection = collect([1, 2, 3, 4]);
const subset = collection.takeUntil(3);
subset.all();
// [1, 2]
takeWhile()
: The takeWhile() method returns items in the collection until the given callback returns false:const collection = collect([1, 2, 3, 4]);
const subset = collection.takeWhile(item => item < 3);
subset.all();
// [1, 2]
times()
: The times() method creates a new collection by invoking the callback a given amount of times:const collection = collect().times(10, number => number * 9);
collection.all();
// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]
toArray()
: The toArray() method converts the collection into a plain array. If the collection is an object, an array containing the values will be returned.const collection = collect([1, 2, 3, 'b', 'c']);
collection.toArray();
// [1, 2, 3, 'b', 'c']
const collection = collect({
name: 'Elon Musk',
companies: ['Tesla', 'Space X', 'SolarCity'],
});
collection.toArray();
// ['Elon Musk', ['Tesla', 'Space X', 'SolarCity']]​
toJson()
: 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"}
unique()
: 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]
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' },
// ]
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(item => 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' },
// ]
unless()
: The unless() method will execute the given callback when the first argument given to the method evaluates to false:const collection = collect([1, 2, 3]);
collection.unless(false, items => items.push(4));
collection.all();
// [1, 2, 3, 4]
unlessEmpty()
: Alias for the whenNotEmpty() method
unlessNotEmpty()
: Alias for the whenEmpty() method
when()
: 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, items => items.push(4));
collection.all();
// [1, 2, 3, 4]
whenEmpty()
: The whenEmpty() method will execute the given callback when the collection is empty:const collection = collect([]);
collection.whenEmpty(c => c.push('Mohamed Salah'));
collection.all();
// ['Mohamed Salah']
const collection = collect(['Darwin Núñez']);
collection.whenEmpty(
c => c.push('Mohamed Salah'),
c => c.push('Xherdan Shaqiri'),
);
collection.all();
// [
// 'Darwin Núñez',
// 'Xherdan Shaqiri',
// ];
whenNotEmpty()
: The whenNotEmpty() method will execute the given callback when the collection is not empty:const collection = collect(['Darwin Núñez']);
collection.whenNotEmpty(c => c.push('Mohamed Salah'));
collection.all();
// [
// 'Darwin Núñez',
// 'Mohamed Salah',
// ]
const collection = collect(['Darwin Núñez']);
collection.whenNotEmpty(
c => c.push('Mohamed Salah'),
c => c.push('Xherdan Shaqiri'),
);
collection.all();
// [
// 'Darwin Núñez',
// 'Mohamed Salah',
// ];
where()
: The where() method filters the collection by a given key / value pair:const collection = collect([
{ product: 'Desk', price: 200, discounted: true },
{ product: 'Chair', price: 100, discounted: true },
{ product: 'Bookcase', price: 150, discounted: true },
{ product: 'Door', price: 100 },
]);
const filtered = collection.where('price', 100);
filtered.all();
// [
// { product: 'Chair', price: 100 },
// { product: 'Door', price: 100 },
// ]
const discounted = collection.where('discounted');
discounted.all();
// [
// { product: 'Desk', price: 200, discounted: true },
// { product: 'Chair', price: 100, discounted: true },
// { product: 'Bookcase', price: 150, discounted: true },
// ]
const notDiscounted = collection.where('discounted', false);
discounted.all();
// [
// { product: 'Door', price: 100 },
// ]
where() method
allows dot notated keys. E.g. where('product.category', 'office-supplies')
The where method also allows for custom comparisons:const filtered = collection.where('price', '!==', 100);
filtered.all();
// [
// { product: 'Desk', price: 200 },
// { product: 'Bookcase', price: 150 },
// ]
const filtered = collection.where('price', '<', 100);
filtered.all();
// []
const filtered = collection.where('price', '<=', 100);
filtered.all();
// [
// { product: 'Chair', price: 100 },
// { product: 'Door', price: 100 },
// ]
const filtered = collection.where('price', '>', 100);
filtered.all();
// [
// { product: 'Desk', price: 200} ,
// { product: 'Bookcase', price: 150 },
// ]
const filtered = collection.where('price', '>=', 150);
filtered.all();
// [
// { product: 'Desk', price: 200} ,
// { product: 'Bookcase', price: 150 },
// ]
Sources : Collect.js, more,.