Scenario:
- you have an array,
- you have an array of some ids (eg: [1,3]),
- you want to get a shortened array.
I cannot find how to do so if not in the lengthy way:
_.filter(... function (id) { return id==1 || id==3 })
Question: does such someMethod1
exist in underscore.js?
var frdsArr =
[
{id: 1, name: 'moe', age: 40},
{id: 2, name: 'larry', age: 50},
{id: 3, name: 'curly', age: 60}
];
var goodFrdsArr = _.someMethod1( frdsArr, 'id', [1, 3] );
/*
goodFrdsArr is [
{id: 1, name: 'moe', age: 40},
{id: 3, name: 'curly', age: 60}
];
*/
The same question with backbone.js: what about someMethod2
?
var Friend = Backbone.Model.extend({});
var FriendsCollection = Backbone.Collection.extend({
model: Friend
});
var friendsCollection = new FriendsCollection( frdsArr );
var goodFriendsCollection = friendsCollection.someMethod2( 'id', [1,3] );
/*
goodFriendsCollection contains 2 instances of Friend Models
*/
Once you have found a suitable function, you can extend Underscore with
_.mixin
to simplify later calls. For example, you could create_.restrict
to match your_.someMethod1
signature:See http://jsfiddle.net/nikoshr/cf0qs5gh/ for a demo
With this setup, you can modify
Backbone.Collection
's prototype to give all your collections this new capacity (more or less taken from the Backbone source code):http://jsfiddle.net/nikoshr/cf0qs5gh/1/
Make use of filter and contains
FIDDLE