jQuery unique objects based on specific object properties
Try this:
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)
For documentation, using 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);
}
});
See demo
As a function:
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;
}
Distinct by multiple properties:
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;
}