2

That returns an empty array. I have also tried using the array of selectedRules[0] itself but got same result. How can we do the comparison of filter on an array of objects against an array of strings to return an array of objects with each filtered rule?

   const allRules = [
      {
       RuleName: "Two",
      RuleId: 2
        },
        {
          RuleName: "Three",
         RuleId: 3
        },
      {
        RuleName: "Four",
        RuleId:4
      }
    ];

    const selectedRules = ["2", "3"]

    const filteredRule = allRules.filter(x => x.RuleId === selectedRules)

    console.log(filteredRule) // []
1
  • The question you are asking is not very clear. Please provide steps that you are taking, what is the outcome and what do you expect to happen? Questions should be phrased in such a way that assumes the reader knows nothing about your implementation. Commented May 1, 2020 at 0:54

1 Answer 1

2

You need to

  • Convert the rules to the same type so that comparison works (a string won't be === to a number)
  • Check whether the selectedRules array .includes the RuleId value being iterated over:

const allRules = [{
    RuleName: "Two",
    RuleId: 2
  },
  {
    RuleName: "Three",
    RuleId: 3
  },
  {
    RuleName: "Four",
    RuleId: 4
  }
];

const selectedRules = ["2", "3"]

const filteredRule = allRules.filter(x => selectedRules.includes(String(x.RuleId)))

console.log(filteredRule)

Sign up to request clarification or add additional context in comments.

Comments

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.