admin管理员组

文章数量:1328002

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.

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.

Share Improve this question asked Jul 2, 2013 at 15:12 claydiffrientclaydiffrient 1,3063 gold badges19 silver badges35 bronze badges 4
  • 1 You want to just remove the duplicates? Or actually go in and find them? – jcreamer898 Commented Jul 2, 2013 at 15:16
  • 1 _.uniq? – Bergi Commented Jul 2, 2013 at 15:23
  • @Bergi _.uniq worked in this specific instance great. But I'm still looking to see if there is a way to determine if it exists within it. – claydiffrient Commented Jul 2, 2013 at 15:58
  • what would be if i want to remove the duplicates matching some object properties the userid and courseid? – Marcel Djaman Commented Jan 28, 2014 at 17:25
Add a ment  | 

1 Answer 1

Reset to default 5

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);

本文标签: javascriptUnderscore contains based on object propertyStack Overflow