-1

I would like to apply two conditions into an array filter.

Actually, I have this code:

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

How can I specify that I need to filter the color AND the name?

2

2 Answers 2

0

You could write a little utility for combining predicates:

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

In general both boolean conjunction and disjunction form monoids, and monoid returning functions also form monoids. So if you're using some functional programming library you could also do:

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

const result = input.filter(arr.fold(fn(and))(preds))
Sign up to request clarification or add additional context in comments.

Comments

0

Use && operator to check both conditions

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>

2 Comments

So I need to use a.color and a.name and not b.name? Why?
because a is the parameter of the callback which represents the individual element of the array and not b

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.