动态过滤器:使用.filter()

时间:2019-03-09 18:56:36

标签: javascript 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);

我正在尝试基于key:value中传递的getgetFilteredUsers()创建一个动态过滤器,将给出相应的输出。

目前,getgetFilteredUsers()仅在计算equals to。但是我想使用相同的函数比较所有三个比较,即等于,小于和大于。

3 个答案:

答案 0 :(得分:5)

一种替代方法是传递谓词,该谓词将由函数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; }

答案 1 :(得分:1)

您可以采用比较功能并移交所需功能,或者将equal比较作为默认功能。

const
    equal = (a, b) => a === b,
    lt = (a, b) => a < b,
    gt = (a, b) => a > b,
    filter = (array, key, value, cf = equal) => array.filter(x => cf(x[key], value));

var 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' }],
    user28 = filter(users, "age", 28),
    userLT28 = filter(users, "age", 28, lt);

console.log(user28);
console.log(userLT28);

答案 2 :(得分:1)

您可以使用一个对象来保存您的操作并将该对象编入索引,以获取适用于该操作的正确函数:

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'));