Collect.js is a JavaScript library that provides a convenient and expressive API for working with arrays and objects, similar to Laravel's Collections in PHP.
It simplifies common array and object operations like filtering, sorting, and transforming, making code more readable and concise.
In this tutorial, we will cover:
- What is Collect.js?
- Installation and Setup
- Creating Collections
- Accessing and Retrieving Values
- Manipulating Collections
- Filtering Collections
- Sorting Collections
- Transforming Collections
- Examples and Use Cases
Let’s dive into each section with examples.
Table of Contents
1. What is Collect.js?
Collect.js is a collection library that makes it easier to work with arrays and objects. It offers a rich API for manipulating data, allowing you to perform complex operations using method chaining.
Some key features of Collect.js:
- Simple and expressive API.
- Chainable methods for performing multiple operations.
- Works with both arrays and objects.
2. Installation and Setup
Installation via npm:
You can install Collect.js using npm or yarn:
npm install collect.js
or
yarn add collect.js
Importing Collect.js into your project:
const collect = require('collect.js'); // ES6 Import // import collect from 'collect.js';
3. Creating Collections
A collection is a wrapper around an array or object, providing useful methods for manipulating the data. To create a collection, use the collect() function.
Example 1: Creating a Collection from an Array
const numbers = [1, 2, 3, 4, 5]; const collection = collect(numbers); console.log(collection.all()); // Output: [1, 2, 3, 4, 5]
Example 2: Creating a Collection from an Object
const user = { name: 'John', age: 30, city: 'New York' }; const collection = collect(user); console.log(collection.all()); // Output: { name: 'John', age: 30, city: 'New York' }
4. Accessing and Retrieving Values
Collect.js provides methods to easily access and retrieve values from a collection.
Example 1: Accessing a Value by Key
const user = { name: 'John', age: 30, city: 'New York' }; const collection = collect(user); console.log(collection.get('name')); // Output: John console.log(collection.get('age')); // Output: 30
Example 2: Retrieving the First and Last Elements
const numbers = [10, 20, 30, 40, 50]; const collection = collect(numbers); console.log(collection.first()); // Output: 10 console.log(collection.last()); // Output: 50
Example 3: Checking if a Collection is Empty
const numbers = []; const collection = collect(numbers); console.log(collection.isEmpty()); // Output: true console.log(collection.isNotEmpty()); // Output: false
5. Manipulating Collections
Collect.js provides a variety of methods for manipulating collections, including adding, removing, and modifying values.
Example 1: Adding Values to a Collection
const numbers = [1, 2, 3]; const collection = collect(numbers); // Add an item to the end of the collection collection.push(4); console.log(collection.all()); // Output: [1, 2, 3, 4]
Example 2: Removing Values from a Collection
const numbers = [1, 2, 3, 4]; const collection = collect(numbers); // Remove the last item collection.pop(); console.log(collection.all()); // Output: [1, 2, 3] // Remove the first item collection.shift(); console.log(collection.all()); // Output: [2, 3]
Example 3: Combining Collections
You can merge two or more collections into one.
const collection1 = collect([1, 2]); const collection2 = collect([3, 4]); const combined = collection1.concat(collection2); console.log(combined.all()); // Output: [1, 2, 3, 4]
6. Filtering Collections
The filter() method allows you to filter the collection by a callback function.
Example 1: Filtering Numbers Greater than a Given Value
const numbers = [1, 2, 3, 4, 5, 6]; const collection = collect(numbers); // Filter numbers greater than 3 const filtered = collection.filter(num => num > 3); console.log(filtered.all()); // Output: [4, 5, 6]
Example 2: Filtering Objects in a Collection
const users = [ { name: 'John', age: 30 }, { name: 'Jane', age: 25 }, { name: 'Tom', age: 35 } ]; const collection = collect(users); // Filter users older than 30 const filtered = collection.filter(user => user.age > 30); console.log(filtered.all()); // Output: [{ name: 'Tom', age: 35 }]
7. Sorting Collections
The sort() method allows you to sort collections by value or key.
Example 1: Sorting Numbers in Ascending Order
const numbers = [5, 3, 8, 1]; const collection = collect(numbers); // Sort the collection in ascending order const sorted = collection.sort(); console.log(sorted.all()); // Output: [1, 3, 5, 8]
Example 2: Sorting by Object Properties
const users = [ { name: 'John', age: 30 }, { name: 'Jane', age: 25 }, { name: 'Tom', age: 35 } ]; const collection = collect(users); // Sort by age const sorted = collection.sortBy('age'); console.log(sorted.all()); // Output: [ // { name: 'Jane', age: 25 }, // { name: 'John', age: 30 }, // { name: 'Tom', age: 35 } // ]
8. Transforming Collections
The map() method allows you to transform each item in the collection using a callback function.
Example 1: Doubling Each Number in the Collection
const numbers = [1, 2, 3]; const collection = collect(numbers); // Double each number const doubled = collection.map(num => num * 2); console.log(doubled.all()); // Output: [2, 4, 6]
Example 2: Transforming Object Properties
const users = [ { name: 'John', age: 30 }, { name: 'Jane', age: 25 } ]; const collection = collect(users); // Increment each user's age by 1 const incrementedAges = collection.map(user => { user.age += 1; return user; }); console.log(incrementedAges.all()); // Output: [ // { name: 'John', age: 31 }, // { name: 'Jane', age: 26 } // ]
9. Examples and Use Cases
Example 1: Counting the Occurrences of Values
You can count how many times each value appears in a collection.
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana']; const collection = collect(fruits); const counts = collection.countBy(); console.log(counts.all()); // Output: { apple: 2, banana: 2, orange: 1 }
Example 2: Grouping Data by a Key
You can group a collection of objects by a given key using groupBy().
const users = [ { name: 'John', age: 30 }, { name: 'Jane', age: 25 }, { name: 'Tom', age: 30 } ]; const collection = collect(users); // Group by age const grouped = collection.groupBy('age'); console.log(grouped.all()); // Output: // { // '25': [{ name: 'Jane', age: 25 }], // '30': [{ name: 'John', age: 30 }, { name: 'Tom', age: 30 }] // }
Example 3: Reducing a Collection to a Single Value
You can reduce a collection to a single value using the reduce() method.
const numbers = [1, 2, 3, 4, 5]; const collection = collect(numbers); // Calculate the sum of all numbers const sum = collection.reduce((total, num) => total + num, 0); console.log(sum); // Output: 15
Summary of Collect.js Key Methods
Method | Description |
---|---|
all() | Returns all items in the collection. |
get(key) | Retrieves an item by key (for objects). |
first() / last() | Retrieves the first or last item in the collection. |
isEmpty() / isNotEmpty() | Checks if the collection is empty or not. |
push() / pop() | Adds an item to the end of the collection or removes the last item. |
shift() | Removes the first item from the collection. |
concat() | Combines two or more collections. |
filter() | Filters the collection using a callback function. |
sort() / sortBy(key) | Sorts the collection by value or by a specific key (for objects). |
map() | Transforms each item in the collection using a callback function. |
groupBy(key) | Groups items in the collection by a specific key. |
reduce() | Reduces the collection to a single value using a callback function. |
countBy() | Counts the occurrences of values in the collection. |
Conclusion
Collect.js is a powerful and expressive library that simplifies working with arrays and objects in JavaScript. In this tutorial, we covered:
- Creating and retrieving collections from arrays and objects.
- Manipulating collections by adding, removing, and transforming data.
- Filtering and sorting collections based on specific conditions.
- Using advanced methods like groupBy(), map(), reduce(), and countBy().