使用两个条件的数组过滤器[重复]

问题描述 投票:-1回答:2

这个问题在这里已有答案:

我想在array filter中应用两个条件。

实际上,我有这个代码:

arr = arr.filter(
    a => a.color != $(this).data('color'),
    b => b.name != $(this).data('name')
);

如何指定我需要过滤颜色和名称?

javascript arrays
2个回答
0
投票

您可以编写一个用于组合谓词的小实用程序:

const pred = (() => {
  const and = p1 => p2 => x => p1(x) && p2(x)
  const or = p1 => p2 => x => p1(x) || p2(x)

  return { and, or }
})()

// ...

const isntSomeColor = a => a.color != $(this).data('color')
const isntSomeName = b => b.name != $(this).data('name')

const result = input.filter(pred.and(isntSomeColor)(isntSomeName))

通常,布尔连接和析取形成幺半群,并且幺半群返回函数也形成幺半群。因此,如果您正在使用某些函数式编程库,您还可以执行以下操作:

const preds = [
  a => a.color != $(this).data('color'),
  b => b.name != $(this).data('name')
]

const result = input.filter(arr.fold(fn(and))(preds))

0
投票

使用&&运算符检查两个条件

let arr = [
{color: 'blue', name: 'sky'},
{color: 'red', name: 'foo'},
{color: 'yellow', name: 'submarine'},
{color: 'red', name: 'velvet'}
];

arr = arr.filter(a => a.color !== $('#example').data('color') && a.name !== $('#example1').data('name'));

console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="example" data-name="sky" data-color="blue">
</div>
© www.soinside.com 2019 - 2024. All rights reserved.