I didn't see this in underscore already so I wanted to throw this out there.
I found this useful when I do things like building a list of recommended books based on the books a user has viewed, liked, or their friends liked. Then show them a unique list of likely recommendations.
function distinct(items, prop) {
var unique = [];
var distinctItems = [];
_.each(items, function(item) {
if (unique[item[prop]] === undefined) {
distinctItems.push(item);
}
unique[item[prop]] = 0;
});
return distinctItems;
}
// likedBooks + viewedBooks + friendLikedBooks + friendViewedBooks
var books = [
{ name: 'Holes', id: 1 },
{ name: 'Treasure Island', id: 2 },
{ name: 'Holes', id: 2 }
];
var uniqueBooks = distinct(books, 'id');
console.log(uniqueBooks);
/**
var uniqueBooks = [
{ name: 'Holes', id: 1 },
{ name: 'Treasure Island', id: 2 }
];
*/
I'd love to come up with a more appropriate PR but I wanted to see what people thought first.
You can accomplish that with the following, though you can't use the property name shorthand.
_.uniq(books, function(book) { return book.id; })
Ty @braddunbar Didn't think I could do that from the docs. Would be really helpful as a second example there.
http://underscorejs.org/#uniq
The new _.property method should be able to solve this use case quite nicely.
Most helpful comment
You can accomplish that with the following, though you can't use the property name shorthand.