Collect.js partition() Method
Last Updated :
30 Nov, 2020
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
const collect = require( 'collect.js' );
const collection = collect([1, 2, 3,
5, 6, 8, 9, 11, 17, 22]);
const [odd, even] = collection.partition(
element => element % 2 != 0);
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
const collect = require( 'collect.js' );
const collection = collect([ 'Welcome' ,
'Geeks' , 'GFG' , 'GeeksforGeeks' ]);
const [short, long] = collection.partition(
element => element.length < 6);
console.log(short.all());
console.log(long.all());
|
Run the index.js file using the following command:
node index.js
Output:
[ 'Geeks', 'GFG' ]
[ 'Welcome', 'GeeksforGeeks' ]
Share your thoughts in the comments
Please Login to comment...