我有一个包含许多对象(药物)的数组。每个对象有3个键:“Drug1”,“Drug2”和riskkingRate。如果Drug1和Drug2值相同,我如何删除重复的对象(riskkingRate在查找重复项时并不重要)。然后保持具有更高冒险率的对象并移除其他对象。这是一个简单的数组:
var Warfarin = [{
"Drug1": "Warfarin",
"Drug2": "vitamin K",
"riskRating": "C",
}, {
"Drug": "aspirin",
"Drug2": "MiFEPRIStone",
"riskRating": "C",
}, {
"Drug1": "Warfarin",
"Drug2": "Omacetaxine",
"riskRating": "X",
}, {
"Drug1": "Warfarin",
"Drug2": "vitamin K",
"riskRating": "X",
},{
"Drug1": "Warfarin",
"Drug2": "vitamin K",
"riskRating": "A",
}]
在此示例中,对象0,3和4是重复的,对象3具有更高的riskkingRate。 (冒险率X> D> C> B> A)。如何删除对象0和4并保留对象1,2和3。 感谢。
答案 0 :(得分:3)
您可以这样做:
var weights = ["X", "D", "C", "B", "A"];
var Warfarin = [{
"Drug1": "Warfarin",
"Drug2": "vitamin K",
"riskRating": "C",
}, {
"Drug": "aspirin",
"Drug2": "MiFEPRIStone",
"riskRating": "C",
}, {
"Drug1": "Warfarin",
"Drug2": "Omacetaxine",
"riskRating": "X",
}, {
"Drug1": "Warfarin",
"Drug2": "vitamin K",
"riskRating": "X",
},{
"Drug1": "Warfarin",
"Drug2": "vitamin K",
"riskRating": "A",
}];
var response = Warfarin.sort((v1, v2) => (weights.indexOf(v1.riskRating) - weights.indexOf(v2.riskRating)))
.reduce((a, c)=>{
if(!a.some(v => (v.Drug1 == c.Drug1 && v.Drug2 == c.Drug2))){
a.push(c);
}
return a;
}, []);
console.log(response);
这样做的目的是首先根据对象'riskRating
对数组进行排序,以便更高风险的对象在开始时,然后只减少数组并且不在结果数组中包含重复项。
答案 1 :(得分:3)
这是一个没有排序的解决方案,但是使用ES6 Map
,这将使其在 O(n)时间内运行而不是 O(nlogn):
const Warfarin = [{"Drug1": "Warfarin","Drug2": "vitamin K","riskRating": "C",}, {"Drug": "aspirin","Drug2": "MiFEPRIStone","riskRating": "C",}, {"Drug1": "Warfarin","Drug2": "Omacetaxine","riskRating": "X",},{"Drug1": "Warfarin","Drug2": "vitamin K","riskRating": "X",},{"Drug1": "Warfarin","Drug2": "vitamin K","riskRating": "A",}];
const result = Array.from(Warfarin.reduce ( (acc, obj) => {
const key = JSON.stringify([obj.Drug1,obj.Drug2]);
return !acc.has(key) || acc.get(key).riskRating < obj.riskRating
? acc.set(key, obj) : acc;
}, new Map).values());
console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;