1

I want to use filter1 and filter2 functions in generalFilter but I can't comprehend the right syntax to do it in Javascript.

const filter1 = (
  array
) => {

  return array.filter((parameter, index) => {
    return (
      !parameter.isOptional()
    );
  });
};

const filter2 = (
  array
) => {

  return array.filter((parameter, index) => {
    return (
      !parameter.isEmpty()
    );
  });
};

const filterGeneral = (
  array
) => {
  return array.filter(filter1(array) && filter2(array));
};

This is apprx. what I am trying to do but I am not able to manage to succeed, and I didn't like my logic. Is there any way to do this properly?

1
  • array.filter(func1).filter(func2) Commented Mar 20, 2020 at 13:36

3 Answers 3

4

You could use a pipe function, where you take some function and take the result from the first function as input for the second function, and so on.

const
    pipe = (...functions) => input => functions.reduce((acc, fn) => fn(acc), input),
    filter1 = array => array.filter((parameter, index) => !parameter.isOptional()),
    filter2 = array => array.filter((parameter, index) => !parameter.isEmpty()),
    filterGeneral = pipe(filter1, filter2),
    array = [{ ... }, { ... }],
    result = filterGeneral(array);
Sign up to request clarification or add additional context in comments.

2 Comments

Very intersting approach, why (if it is) is this better than just chaining multiple filter functions?
it works with any type, because it is independent of array's prototype functions.
2

Has they are two different filters, you can only apply one at a time over the parameter itself, so I think you should apply one to another:

const filterGeneral = array => filter1(filter2(array));

1 Comment

I would probably filter first by filter1 then filter2.
1

You can just chain multitple filter() methods like this:

const array = [1, 2, 3, 4, 5];

array.filter((elem) => elem > 2).filter((elem) => elem > 3);
// returns [4, 5]

This works because Array.prototype.filter() returns the filtered array. You can just filter this array again.

This means that the example above is the same as writing this:

const array = [1, 2, 3, 4, 5]
const tmp = array.filter((elem) => elem > 2);
tmp.filter((elem) => elem > 3);

2 Comments

The functions do the acual filtering, so it doesn't make sense to pass them into .filter as a callback.
@Andy I just realised right after hitting answer and edited my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.