Last Updated: February 25, 2016
·
606
· bryanmikaelian

Filtering on IDs in JavaScript

In Backbone, you are often working with a collection of models that have their own ID. However, you might run in to a scenario where you only need models from the collection that have a certain property or ID. I do this a lot at my job when it comes to filtering out users that have set a preference to make all their data private.

Here is how we have been doing it with Underscore.js and it has been working out quite nicely:

// Specific data to this example
// Assume users is some backbone collection you have
var users_with_private_data = [{id: 1}, {id: 5}]; 

var private_user_ids  = _.pluck(users_with_private_data, "id");
var filtered_users = _.filter(users.toJSON(), function(user) {
    return _.indexOf(private_user_ids, user.id) === -1
 });

// Do something with the filtered users....