我想要一组唯一对象,删除具有某些特定属性值的重复对象。例如:在下面的代码片段中,event1和event2具有相同的标题和相同的起始值,event3和event4具有相同的标题但开始时间不同。
我想从对象数组中删除event2(因为它与event1具有相同的标题和起始值),但不是event4(因为它只有相同的标题)。
我的代码如下:
var event1 = {id: 1, title: 'ABC', start: '10'};
var event2 = {id: 2, title: 'ABC', start: '10'};
var event3 = {id: 3, title: 'DEF', start: '12'};
var event4 = {id: 4, title: 'DEF', start: '20'};
var a=[];
a.push(event1);
a.push(event2);
a.push(event3);
a.push(event4);
//I tried this, but this code checks for title only.
var titles = [];
var b = [];
$.each(a, function(index, event) {
if ($.inArray(event.title, titles) === -1) {
titles.push(event.title);
b.push(event);
}
});
console.log(b); //Gives output as [Object { id=1, title="ABC", start="10"}, Object { id=3, title="DEF", start="12"}]
// The right output should be: [Object { id=1, title="ABC", start="10"}, Object { id=3, title="DEF", start="12"}, Object { id=3, title="DEF", start="20"}]
我上面的代码只检查标题。我无法使它适用于两个不同的属性。我在这里先向您的帮助表示感谢。
答案 0 :(得分:14)
试试这个:
var event1 = {id: 1, title: 'ABC', start: '10'};
var event2 = {id: 2, title: 'ABC', start: '10'};
var event3 = {id: 3, title: 'DEF', start: '12'};
var event4 = {id: 4, title: 'DEF', start: '20'};
var events = [event1, event2, event3, event4];
var result = events.reduce(function(memo, e1){
var matches = memo.filter(function(e2){
return e1.title == e2.title && e1.start == e2.start
})
if (matches.length == 0)
memo.push(e1)
return memo;
}, [])
console.log(result)
答案 1 :(得分:3)
对于文档,使用jQuery:
$.each(a, function(index, event) {
var events = $.grep(b, function (e) {
return event.title === e.title &&
event.start === e.start;
});
if (events.length === 0) {
b.push(event);
}
});
请参阅demo
答案 2 :(得分:0)
功能:
function distinctArrayBy(arr, propName) {
var result = arr.reduce(function (arr1, e1) {
var matches = arr1.filter(function (e2) {
return e1[propName] == e2[propName];
})
if (matches.length == 0)
arr1.push(e1)
return arr1;
}, []);
return result;
}
按多个属性区分:
function distinctArrayBy(arr, propNames) {
var result = arr.reduce(function (arr1, e1) {
var matches = arr1.filter(function (e2) {
var matchResult = true;
$.each(propNames, function (index, value) {
matchResult = matchResult && e1[value] == e2[value];
});
return matchResult;
});
if (matches.length == 0)
arr1.push(e1)
return arr1;
}, []);
return result;
}