How to find the number of different values ​​from a collection

Suppose I have a collection like:

{ "id": 1, "name": "jonas", }, { "id": 2, "name": "jonas", }, { "id":3, "name": "smirk", } 

How do I get:

The number of different names, as in this case, 2

Different names, in this case, jonas and a smirk?

+4
source share
1 answer

Using the "Trunk and Support" magic combining collection.pluck and _.uniq :

pluck collection.pluck (attribute)
Pull an attribute from each model in the collection. Equivalent to the calling map and returns the same attribute.

uniq _.uniq (array, [isSorted], [iterator])
Produces a duplicate version of the array, using === to check for equality of objects.
[...]

 var c = new Backbone.Collection([ {id: 1, name: "jonas"}, {id: 2, name: "jonas"}, {id: 3, name: "smirk"} ]); var names = _.uniq(c.pluck('name')); console.log(names.length); console.log(names); 

And the demo http://jsfiddle.net/nikoshr/PSFXg/

+12
source

All Articles