Open In App

Collect.js Introduction

Collect.js is a JavaScript library for collecting data from tree-based structures. This library is used on JavaScript Array and Objects.

Features: Some of the important features of Collect.js are:



Installation: We can install collect.js by following two methods.

Method 1: We can install it using npm. Make sure that you have Node.js and npm installed.



npm install collect-js

Method 2: We can also use it through CDN Links. Go to the https://cdnjs.com/libraries/collect.js and add the following CDN link inside <script> tag.

<script src=”https://cdnjs.cloudflare.com/ajax/libs/collect.js/4.29.3/collect.min.js” integrity=
“sha512eHrXl+YqedGIdIKP5YOueP0z7RfRgmo7R1d8pTvEOhikZIFpD54dXbwp9os9z4hVHVHZeRHw0qfF93lDsQDQA==” crossorigin=”anonymous” referrerpolicy=”no-referrer”></script>

Lets’s see an example of how collect.js works.

Example: In this example, we will see how to create new collection instance using Collect.js make() Function.




// Requiring module
const collect = require('collect.js')
  
// User defined collection
var myCollection = [1,2,3,4,5]
  
function make(items = []) {
    return new this.constructor(items);
}
  
// Creating collection object
const collection = collect(myCollection);
  
// Printing collection
console.log(collection.all());
  
// Make Function call
console.log(make([1,2,3]))

Run the index.js file using the following command:

node index.js

Output:

[ 1, 2, 3, 4, 5 ]
[ 1, 2, 3 ]
Article Tags :