在 Map.groupBy() 與 Object.groupBy() 分多個群組
前言
在先前的 初探 Object.groupBy() 與 初探 Map.groupBy() 介紹了 groupBy() 分群組的功能,但範例都只分了兩個群組,事實是 groupBy() 是可以分多個群組的,在此把學習的過程做個紀錄。
內容
範例如下
const fruits = [
{name:"apples", quantity:300},
{name:"bananas", quantity:500},
{name:"oranges", quantity:200},
{name:"kiwi", quantity:150}
];
//
function myCallback({ quantity }) {
let res = 'default';
if( quantity > 0 && quantity <= 200)
res = 'group1';
else if( quantity > 200 && quantity <= 400)
res = 'group2';
//
return res;
}
//
let result = Map.groupBy( fruits , myCallback );
console.log( result.get('default') );
// [[object Object] {
// name: "bananas",
// quantity: 500
// }]
console.log( result.get('group1') );
// [[object Object] {
// name: "oranges",
// quantity: 200
// }, [object Object] {
// name: "kiwi",
// quantity: 150
// }]
console.log( result.get('group2') );
// [[object Object] {
// name: "apples",
// quantity: 300
// }]
範例使用 Map.groupBy() 來分多個群組,要分多個群組只要在分類的 Function 裡回傳不同的名稱就可以有不同的群組,範例將 0~200 分為 group1 ,201~400 分為 group2 ,剩餘為 default ,這樣結果就會產生出三個群組。Object.groupBy() 也可以用一樣的方法來分多個群組。
參考資料
[ developer.mozilla.org ] Map.groupBy()
[ developer.mozilla.org ] Object.groupBy()
沒有留言:
張貼留言