Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone collection: Retrieve distinct values of a collection

I have backbone collection of models and would like to retrieve the distinct values of a certain property

If I have loaded data like the following into my collection:

[{brand:'audi',id:'1234'},
{brand:'audi',id:'3456'},
{brand:'bmw',id:'3456'}]

I would now want to get the distinct brands from the collection. The result should be:

['audi','bmw']

Looking at the Backbone and Underscore API I don't see anything obvious to achieve this. My current approach would be to use a library like jslinq

Am I missing anything obvious or does somebody have a better suggestion than jslinq?

like image 490
AyKarsi Avatar asked Dec 03 '22 02:12

AyKarsi


1 Answers

You can use pluck and then use uniq (example: http://jsfiddle.net/sCVyN/5/)

pluck

A convenient version of what is perhaps the most common use-case for map: extracting a list of property values.

uniq

Produces a duplicate-free version of the array, using === to test object equality. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an iterator function.

like image 131
CD.. Avatar answered Dec 30 '22 06:12

CD..