Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore findWhere function to find element match condition a or b

I have an array of objects

var arr = [{a:1},{a:5}, {a:6},{a:11}];

I want to use underscore find where function to retrieve object satisfying condition a = 1 or a =11

like:

_findWhere(arr, {a:1} || {a:11})

Anything like this is possible ??

like image 600
anandharshan Avatar asked Dec 11 '22 17:12

anandharshan


2 Answers

find behaves like findWhere in that it returns the first item that passes the search criteria. With find you can use a predicate to specify the search criteria.

var result = _.find(arr, function(item) {
    return item.a == 1 || item.a == 11;
});
like image 109
Gruff Bunny Avatar answered Jan 25 '23 23:01

Gruff Bunny


you can use _.filter for this

var arr = [{a:1}, {a:5}, {a:6}, {a:11}];
_.filter(arr,function(n){return (n.a===1 || n.a===11)});

But there is a better solution which can help you adding as many or as you want. Using _.mixin you can create your own or function

var arr = [{a:1}, {a:5}, {a:6}, {a:11}];
_.mixin({
   or: function(obj,arr,condition){
     return _.chain(arr).where(condition).union(obj).value();
   }
});

_.chain(arr).where({a:1}).or(arr,{a:11}).or(arr,{a:2}).value();//returns 2 objects
_.chain(arr).where({a:1}).or(arr,{a:11}).or(arr,{a:5}).value();//returns 3 objects
_.chain(arr).where({a:1}).or(arr,{a:11}).value();//returns 2 objects

var arr2 = [{a:1,b:4}, {a:5}, {a:6}, {a:11}];
_.chain(arr2).where({a:1}).or(arr2,{a:11}).value();//returns 2 objects
like image 39
Rahul Avatar answered Jan 26 '23 00:01

Rahul