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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With