Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic filter: Creating a dynamic filter using .filter()

let users = [
    { id: 11, name: 'Adam', age: 23, group: 'editor' },
    { id: 47, name: 'John', age: 28, group: 'admin' },
    { id: 85, name: 'William', age: 34, group: 'editor' },
    { id: 97, name: 'Oliver', age: 28, group: 'admin' }
  ];

var getFilteredUsers = (array, key, value) => array.filter(x => x[key] === value);
var FilteredUsers = getFilteredUsers(users, "age", 28);
console.log(FilteredUsers);

I am trying to create a dynamic filter, based on the key:value passed in getgetFilteredUsers() will give the corresponding output.

Right now, getgetFilteredUsers() is only computing equals to. But I want to use this same function to compare all three comparisons i.e equals to, less than and greater than.


2 Answers

An alternative is passing the predicate which will be called by the function filter

let users = [{ id: 11, name: 'Adam', age: 23, group: 'editor' },{ id: 47, name: 'John', age: 28, group: 'admin' },{ id: 85, name: 'William', age: 34, group: 'editor' },{ id: 97, name: 'Oliver', age: 28, group: 'admin' }];
let getFilteredUsers = (array, handler) => array.filter(handler);

let  FilteredUsers = getFilteredUsers(users, x => x['age'] === 28);
console.log(FilteredUsers);

FilteredUsers = getFilteredUsers(users, x => x['age'] > 28);
console.log(FilteredUsers);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 164
Ele Avatar answered Nov 25 '25 01:11

Ele


You can use an object to hold your operations and index this object to get the right function to apply for that operation:

const users = [
  { id: 11, name: 'Adam', age: 23, group: 'editor' },
  { id: 47, name: 'John', age: 28, group: 'admin' },
  { id: 85, name: 'William', age: 34, group: 'editor' },
  { id: 97, name: 'Oliver', age: 28, group: 'admin' }
];

const filterUsers = (arr, key, value, op = 'eq') => {
  const ops = {
    eq: (x, y) => x === y,
    lt: (x, y) => x < y,
    gt: (x, y) => x > y
  };
  return arr.filter(x => ops[op](x[key], value));
};

console.log(filterUsers(users, 'age', 28));
console.log(filterUsers(users, 'age', 28, 'lt'));
console.log(filterUsers(users, 'age', 28, 'gt'));
like image 20
jo_va Avatar answered Nov 25 '25 01:11

jo_va



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!