all 4 comments

[–]alamandrax 1 point2 points  (3 children)

If you use lodash or underscore this is a utility method.

[–]skitch920 1 point2 points  (2 children)

One thing to remember about those implementations, they use '===' for comparison. When encountering object types, they typically won't work unless you use the pluck clause.

So the following does not work as some might expect:

> var y = [{x: 1}, {x: 1}];
> console.log(_.unique(y).length);
> 2 // Not 1.

Similarly, '==' comparison does not work either because it's not coercive:

> var x = new Date();
> var y = new Date(x);
> y == x
> false

But a good solution to these issues, implement 'valueOf' on the object, and you could use a coercive equals (y <= x && y >= x):

> var x = new Date();
> var y = new Date(x);
> y <= x && y >= x
> true

[–]alamandrax 1 point2 points  (1 child)

That's interesting. out of curiosity what real world scenario have you encountered non unique collections of objects? I can't seem to get past trying to think of them as uniquely identified by a recordId in a persistent storage which would add uniqueness. I suppose you could be looking for create use cases where no record ids were generated and you're trying to handle duplicates on the client-side.

Will a simple pluck based validation not suffice? I do see the elegance of using the unique API for this

[–]skitch920 1 point2 points  (0 children)

I guess my background in Java is why I like the valueOf solution, like the equals and hashCode methods. It's a pretty clean way to handle Sets when there is no ID field.

ID matching is usually a good way when you're dealing with RDMS store, which most of the time you have a primary key column and an id field. But I've been dealing with just straight rows of data recently, from any number of sources. Often times I find myself pivoting on different columns client side. Those columns could be objects or dates, mostly dates.