Unique jQuery objects based on specific object properties

I want an array of unique objects, removing duplicate objects that have specific property values. For example: in the code snippet below, events1 and event2 have the same title and same initial value, event3 and event4 have the same name, but different start times.

I want to remove event2 from an array of objects (since it has the same header and initial value as event1), but not event4 (since it has only one header).

My code looks like 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 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"}] 

My code above only checks the title. I could not get it to work for two different properties. Thanks for the help in advance.

+6
source share
3 answers

Try the following:

 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) 
+14
source

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); } }); 

Watch the demo

+4
source

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; } 

Differ in several 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; } 
0
source

Source: https://habr.com/ru/post/1207908/


All Articles