Collect.js partition() Method
The partition() method is used to separate the collection elements according to the given callback function. The first array containing those elements that satisfy the predicate (condition) and the second array contains the remaining elements.
Syntax:
collect(array).partition(callback)
Parameters: The collect() method takes one argument that is converted into the collection and then the partition() method is applied to it. The partition() method holds the callback function as a parameter.
Return Value: This method returns the collection elements with partition.
Module Installation: Install collect.js module using the following command from the root directory of your project:
npm install collect.js
The below example illustrates the partition() method in collect.js:
Example 1: Filename: index.js
Javascript
// Requiring the module const collect = require( 'collect.js' ); // Creating collection object const collection = collect([1, 2, 3, 5, 6, 8, 9, 11, 17, 22]); // Calling partition function on collection const [odd, even] = collection.partition( element => element % 2 != 0); // Printing the odd & even values console.log(odd.all()); console.log(even.all()); |
Run the index.js file using the following command:
node index.js
Output:
[ 2, 6, 8, 22 ] [ 1, 3, 5, 9, 11, 17 ]
Example 2: Filename: index.js
Javascript
// Requiring the module const collect = require( 'collect.js' ); // Creating collection object const collection = collect([ 'Welcome' , 'Beginner' , 'GFG' , 'w3wiki' ]); // Calling partition function on // collection object const [short, long] = collection.partition( element => element.length < 6); // Printing short values console.log(short.all()); // Printing long values console.log(long.all()); |
Run the index.js file using the following command:
node index.js
Output:
[ 'Beginner', 'GFG' ] [ 'Welcome', 'w3wiki' ]
Contact Us