Collect.js
💎 Convenient and dependency free wrapper for working with arrays and objects
Install / Use
/learn @ecrmnn/Collect.jsREADME
<img src="https://raw.githubusercontent.com/ecrmnn/collect.js/master/collectjs.jpg" alt="collect.js">
Convenient and dependency free wrapper for working with arrays and objects
Installation
NPM
npm install collect.js --save
Yarn
yarn add collect.js
From CDN
- Visit https://cdnjs.com/libraries/collect.js
- Add CDN link to your site with
<script>
Using build / minified version
- Download
collect.min.js - Add to your site with
<script>
Tip
Using Laravel as your backend? Collect.js offers an (almost) identical api to Laravel Collections. See differences.
API
All available methods
- all
- average
- avg
- chunk
- collapse
- combine
- concat
- contains
- containsOneItem
- count
- countBy
- crossJoin
- dd
- diff
- diffAssoc
- diffKeys
- diffUsing
- doesntContain
- dump
- duplicates
- each
- eachSpread
- every
- except
- filter
- first
- firstOrFail
- firstWhere
- flatMap
- flatten
- flip
- forPage
- forget
- get
- groupBy
- has
- implode
- intersect
- intersectByKeys
- isEmpty
- isNotEmpty
- join
- keyBy
- keys
- last
- macro
- make
- map
- mapInto
- mapSpread
- mapToDictionary
- mapToGroups
- mapWithKeys
- max
- median
- merge
- mergeRecursive
- min
- mode
- nth
- only
- pad
- partition
- pipe
- pluck
- pop
- prepend
- pull
- push
- put
- random
- reduce
- reject
- replace
- replaceRecursive
- reverse
- search
- shift
- shuffle
- skip
- skipUntil
- skipWhile
- slice
- sole
- some
- sort
- sortBy
- sortByDesc
- sortDesc
- sortKeys
- sortKeysDesc
- splice
- split
- sum
- take
- takeUntil
- takeWhile
- tap
- times
- toArray
- toJson
- transform
- undot
- union
- unique
- unless
- unlessEmpty
- unlessNotEmpty
- unwrap
- values
- when
- whenEmpty
- whenNotEmpty
- where
- whereBetween
- whereIn
- whereInstanceOf
- whereNotBetween
- whereNotIn
- whereNotNull
- whereNull
- wrap
- zip
Strictness and comparisons
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.
Methods that have not been implemented:
- ~~
containsStrict~~ usecontains() - ~~
duplicatesStrict~~ useduplicates() - ~~
uniqueStrict~~ useunique() - ~~
whereStrict~~ usewhere() - ~~
whereInStrict~~ usewhereIn() - ~~
whereNotInStrict~~ usewhereNotIn()
all()
The all method returns the underlying array or object represented by the collection:
collect([1, 2, 3]).all();
// [1, 2, 3]
collect({
firstname: 'Darwin',
lastname: 'Núñez',
}).all();
// {
// firstname: 'Darwin',
// lastname: 'Núñez',
// }
average()
Alias for the avg() method
avg()
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: 'My story',
pages: 176,
},
{
name: 'Fantastic Beasts and Where to Find Them',
pages: 1096,
},
]);
collection.avg('pages');
// 636
You may also define a callback function
const collection = collect([
{
name: 'My story',
pages: 176,
},
{
name: 'Fantastic Beasts and Where to Find Them',
pages: 1096,
},
]);
collection.avg(book => book.pages);
// 636
chunk()
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]]
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(['Mohamed Salah', 11]);
combine.all();
// {
// name: 'Mohamed Salah',
// number: 11
// }
concat()
The concat method is used to merge two or more collections/arrays/objects:
You can also concat() an array of objects, or a multidimensional array
const collection = collect([1, 2, 3]);
let concatenated = collection.concat(['a', 'b', 'c']);
concatenated = concatenated.concat({
name: 'Mohamed Salah',
number: 11,
});
concatenated.all();
// [1, 2, 3, 'a', 'b', 'c', 'Mohamed Salah', 11]
contains()
The contains method determines whether the collection contains a given item:
const collection = collect({
name: 'Mohamed Salah',
number: 11,
});
collection.contains('name');
// true
collection.contains('age');
// false
collection.contains('Mohamed Salah');
// true
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: 'Mohamed Salah',
number: 11,
});
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((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,
// }
However, you pass a callback to the countBy method to count all items by a custom value:
const collection = collect([
'mohamed.salah@gmail.com',
'darwin.nunez@yahoo.com',
'roberto.firmino@gmail.com',
]);
const counted = collection.countBy(email => email.split('@')[1]);
counted.all();
// {
// 'gmail.com': 2,
// 'yahoo.
Related Skills
node-connect
336.5kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
82.9kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
336.5kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
commit-push-pr
82.9kCommit, push, and open a PR
