Underscore: (idea) Unique array of objects by property

Created on 10 Dec 2013  路  3Comments  路  Source: jashkenas/underscore

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.

question

Most helpful comment

You can accomplish that with the following, though you can't use the property name shorthand.

_.uniq(books, function(book) { return book.id; })

All 3 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dmaicher picture dmaicher  路  9Comments

afranioce picture afranioce  路  8Comments

acl0056 picture acl0056  路  5Comments

xiaoliwang picture xiaoliwang  路  3Comments

jdalton picture jdalton  路  4Comments