Skip to content

ecrmnn/collect.js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

collect.js

Convenient and dependency free wrapper for working with arrays and objects

Build Status npm version npm downloads npm license PRs Welcome dependencies eslint cdnjs version

Installation

NPM

npm install collect.js --save

Yarn

yarn add collect.js

From CDN

  1. Visit https://cdnjs.com/libraries/collect.js
  2. Add CDN link to your site with <script>

Using build / minified version

  1. Download collect.min.js
  2. 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

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 use contains()
  • duplicatesStrict use duplicates()
  • uniqueStrict use unique()
  • whereStrict use where()
  • whereInStrict use whereIn()
  • whereNotInStrict use whereNotIn()

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.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' }

diffUsing()

The diffUsing method compares the collection against another collection or a plain array based on its values using a callback. This method will return the values in the original collection that are not present in the given collection:

const collection = collect([
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 },
]);

const users = [
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 },
  { name: 'David', age: 40 },
];

const diff = collection.diffUsing(users, (a, b) => a.age - b.age);

diff.all();

// [{ name: 'Alice', age: 25 }]

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

You may also use doesntContain on object based collections:

const collection = collect({
  name: 'Mohamed Salah',
  number: 11,
});

collection.doesntContain('Mohamed Salah');
// false

collection.doesntContain('Darwin NĂșñez');
// 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.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

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((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]

For the inverse of 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]

If no callback is supplied, all entries of the collection that are equivalent to 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]

For the inverse of filter, see the reject 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

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

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.

You may also call the firstOrFail method with no arguments to get the first element in the collection. If the collection is empty, an error is thrown:

collect([1, 2, 3, 4]).firstOrFail();

// 1
collect().firstOrFail();

// Error ('Item not found.') is thrown.

Like the where method, you may also pass an attribute, operator, and value:

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: