Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash filter on key with multiple values

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

like image 811
Avi Kenjale Avatar asked Oct 07 '16 16:10

Avi Kenjale


2 Answers

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);
like image 114
Ori Drori Avatar answered Oct 06 '22 00:10

Ori Drori


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;
});
like image 42
Doppio Avatar answered Oct 05 '22 23:10

Doppio