Using DISTINCT to return a list of JSON objects

Mar 16, 2012 at 9:47 PM

Hi there, I'm not sure if I'm missing something here but I'm trying to figure out how to reduce a list of JSON objects down to a unique list using the DISTINCT keyword.

I can do this and return a single array of values but how do I return an array of objects?

e.g. I would like 'bob' below to look exactly the same as 'testList' but without the 3rd item in the array since it has a duplicate ID.....

var testList = [{ ID: 101, NAME: 'Hello' }, { ID: 102, NAME: 'Goodbye' }, { ID: 102, NAME: 'Goodbye'}];
var bob = JSLINQ(testList).Distinct(function (item) { return item.NAME;}).items

//('bob' at this point has lost the ID/NAME part of the objects)

I have tried experimenting with different return syntax in the DISTINCT function but am confused at the seemingly dual functionality of this code. i.e. it defines the Distinct criteria but also my return type?

Any help appreciated!

Oliver.

May 8, 2012 at 8:39 PM

I'm having the same issue.

var myarray = [{Id: 101, Name:User1},{Id: 101, Name:User1},{Id: 102, Name:User2}];

var users = Enumerable.From(myarray).Distinct().ToArray();

returns all the elements in the array, not the distinct elements.

Maybe I'm doing this the wrong way.  

Is there a better or correct way to do this?

Any help is appreciated.

Thanks,

Annie

 

Jun 25, 2013 at 9:12 AM
I have same problem.

It looks like that distinct not work for complex object.

Milan
Coordinator
Jun 25, 2013 at 9:52 AM
sorry, I missed this thread.

var array = [{Id: 101, Name:"a"},{Id: 101, Name:"a"}]
array[0] == array[1] is false.
because array[0] and array[1] is different object(reference).
Distinct's default behavior is compare reference.

If you want to compare complex object, I recommend create string key.
Enumerable.From([{Id: 101, Name:"a"},{Id: 101, Name:"a"},{Id: 102, Name:"b"}]).Distinct("$.Id + '-' + $.Name")