[英]Remove n items from an array with object based on property name
我在這里有這個數組:
result = [{ID:"97",answerA:"Apple", answerB:"Chair",category:"MEAT"} , {ID:"97",answerA:"Apple", answerB:"Chair",category:"MEAT"}];
等等。
到目前為止,我的數組剛好包含5個類別中的20個項目-因此每個類別都包含4個項目。
我想訴諸我的數組,使其包含:
2個類別,= “常規”的項目
根據上述規則,使我的數組僅包含15個項目的最佳方法是什么。
PS:當然,在重新排序后的新陣列中將保留5個項目。
我曾考慮過遍歷該數組並使用IF / Else語句求助一個新語句,但我希望看到執行此操作的最佳和最簡單方法。
最干凈的imo將使用Array.filter()
和計數器來獲取所需的確切類別。
// these are the categories and their allowed maxCounts
var counts = {
"Vegetables": {maxCount: 4, count: 0},
"Fingerfood": {maxCount: 3, count: 0},
//...
};
// filtered is the reduced array containing just the ones you need
var filtered = result.filter(function(_item) {
var c = counts[_item.category];
// include only if allowed as per counts
if(c && c.count < c.maxCount) { c.count++; return true; }
return false;
});
PS:
counts
類別名稱應與result
類別名稱匹配
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.