當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Collect.js partition()用法及代碼示例

partition()方法用於根據給定的回調函數分隔收集元素。第一個數組包含滿足謂詞(條件)的那些元素,第二個數組包含其餘元素。

用法:

collect(array).partition(callback)

參數:collect()方法采用一個參數,該參數將轉換為集合,然後將partition()方法應用於該參數。 partition()方法將回調函數作為參數保存。

返回值:此方法返回帶有分區的集合元素。

模塊安裝:使用以下命令從項目的根目錄安裝collect.js模塊:



npm install collect.js

以下示例說明了collect.js中的partition()方法:

示例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());

使用以下命令運行index.js文件:

node index.js

輸出:

[ 2, 6, 8, 22 ]
[ 1, 3, 5, 9, 11, 17 ]

示例2:Filename:index.js

Javascript

// Requiring the module 
const collect = require('collect.js'); 
  
// Creating collection object 
const collection = collect(['Welcome',  
    'Geeks', 'GFG', 'GeeksforGeeks']); 
  
// 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());

使用以下命令運行index.js文件:

node index.js

輸出:

[ 'Geeks', 'GFG' ]
[ 'Welcome', 'GeeksforGeeks' ]

相關用法


注:本文由純淨天空篩選整理自AshokJaiswal大神的英文原創作品 Collect.js partition() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。