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 ??
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 ??
Share Improve this question edited Mar 25, 2016 at 18:14 Shaffiulla Khan 10.4k16 gold badges57 silver badges54 bronze badges asked Mar 23, 2016 at 17:22 anandharshananandharshan 6,3724 gold badges37 silver badges35 bronze badges4 Answers
Reset to default 8find 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;
});
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
For your case better to use find
function. You can use function that passed as a second argument to find
method and checks your two conditions:
var arr = [{ a: 1 }, { a: 5 }, { a: 6 }, { a: 11 }];
var elem = _.find(arr, function(e) {
return e.a == 1 || e.a == 11;
});
document.write(JSON.stringify(elem));
<script src="https://cdnjs.cloudflare./ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
Or using plain javascript (ES2015
):
var arr = [{ a: 1 }, { a: 5 }, { a: 6 }, { a: 11 }];
var elem = arr.find(function(e) {
return e.a == 1 || e.a == 11;
});
document.write(JSON.stringify(elem));
You could write it in plain Javascript with Array#some
var arr = [{ a: 1 }, { a: 5 }, { a: 6 }, { a: 11 }, { a: 11 }],
found = function (array) {
var index;
return arr.some(function (a, i) {
if (a.a === 1 || a.a === 11) {
index = i;
return true;
}
}) && array[index] || undefined;
}(arr);
document.write('<pre>' + JSON.stringify(found, 0, 4) + '</pre>');