Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find number of distinct values from a collection

Tags:

backbone.js

Suppose I have a collection like:

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

How do I get :

Number of distinct names, like in this case, 2

The distinct names, in this case, jonas and smirk ?

like image 514
JeanFrancois Avatar asked Dec 15 '22 20:12

JeanFrancois


1 Answers

With some Backbone and Underscore magic, combining collection.pluck and _.uniq:

pluck collection.pluck(attribute)
Pluck an attribute from each model in the collection. Equivalent to calling map, and returning a single attribute from the iterator.

uniq _.uniq(array, [isSorted], [iterator])
Produces a duplicate-free version of the array, using === to test object equality.
[...]

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 a demo http://jsfiddle.net/nikoshr/PSFXg/

like image 199
nikoshr Avatar answered Jan 10 '23 03:01

nikoshr