claydiffrient claydiffrient - 1 month ago 7x
Javascript Question

Underscore contains based on object property

I would like to use Underscore.js to determine if an instance of an object is present in an array.

An example usage would be:

var enrollments = [
{ userid: 123, courseid: 456, enrollmentid: 1 },
{ userid: 123, courseid: 456, enrollmentid: 2 },
{ userid: 921, courseid: 621, enrollmentid: 3 }

I want to be able to identify unique an enrollment where the userid and courseid are the same.

So basically, given a list of enrollments I can remove duplicates based on matches to the userid and courseid, but not the enrollment id.


You can use the filter method from Underscore:

function contains(arr, userid, courseid){

 var matches = _.filter(arr, function(value){ 
    if (value.userid == userid && value.courseid == courseid){ 
      return value;

 return matches;

contains(enrollments, 123, 456);