I am trying to find out in lodash
javascript library
, how to find out filter array of objects multiple values of key. something similar to SQL - WHERE KEY in (val1, val2)
Having said, with following example :
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false },
{ 'user': 'Avding', 'age': 34, 'active': true }
];
_.filter(...)
How can I find users, who's age in (34, 36) ?? numbers can also change runtime
Lodash's filter accepts a predicate. You can create the predicate using partial application, so you can change the values easily:
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false },
{ 'user': 'Avding', 'age': 34, 'active': true }
];
var predicate = function(start, end) {
return function(user) {
return _.inRange(user.age, start, end + 1);
}
}
var result = _.filter(users, predicate(34, 36));
console.log('inRange', result);
/** is equal predicate **/
var predicate = function() {
var args = _.toArray(arguments);
return function(user) {
var equalToUserAge = _.partial(_.isEqual, user.age);
return args.some(equalToUserAge);
}
}
var result = _.filter(users, predicate(34, 40));
console.log('equals', result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>
You can also do this easily with vanilla JS as well (the example uses ES6):
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false },
{ 'user': 'Avding', 'age': 34, 'active': true }
];
const predicate1 = (start, end) => ({ age }) =>
age >= start && age <= end;
const result1 = users.filter(predicate1(34, 36));
console.log('in range', result1);
const predicate2 = (...args) => ({ age }) =>
args.some((num) => age === num);
const result2 = users.filter(predicate2(34, 40));
console.log('is equal', result2);
const users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false },
{ 'user': 'Avding', 'age': 34, 'active': true }
];
const minAge = 34;
const maxAge = 36;
const filtered = _.filter(users, (user) => {
return user.age >= minAge && user.age <= maxAge;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With