0

I have 3 ngModel in my UI which are binded in my angular application. All of them are selected by user using multi select dropdown.

country = ["India", "US"]
state = ["Delhi", "MP","UP"]
city = ["gzb","xyz"]

I have a custom filter where i have to filter data based on these responses

filter = {
country: this.country,
state: this.state,
city: this.city
}

result = data.filter(e =>
Object.entries(filters).every(([key,vals])=>vals.includes(e[key])))

There is a scenario where only country array is there and other 2 are empty. Here my filter will fail. How to check null

Test Data

data=[{
"name":"hello",
"gender":"male",
"country":"India",
"state":"Delhi",
"city":"gzb"
}]
3
  • Can you update the question with a testdata for data? Commented Dec 16, 2022 at 10:29
  • Multiple such records just like this. Commented Dec 16, 2022 at 10:35
  • @RahulJain in this answer's comment, they have already mentioned that you need to use vals.length === 0 || vals.includes(...). The snippet is updated. What doesn't work in that? Commented Dec 16, 2022 at 10:37

1 Answer 1

0

You have to check the length of the elements of filter.

If the length off that specific node in filter is zero, then there is no point in checking that filter node, simply return true for that case.

Working Fiddle

const country = ["India", "US"];
// const state = ["Delhi", "MP", "UP"];
const state = [];
const city = ["gzb", "xyz"];
const filter = {
  country,
  state,
  city,
};
const data = [
  {
    name: "hello",
    gender: "male",
    country: "India",
    state: "Delhi",
    city: "gzb",
  },
];
const result = data.filter((e) =>
  Object.entries(filter).every(([key, vals]) => vals.length > 0 ? vals.includes(e[key]) : true)
);
console.log(result);

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

2 Comments

This works. How can i use this in Angular? All the fields are user input and using this snippet give Property 'includes' does not exist on type 'unknown'.
You can just change the variables to your class variables, you can fix this yourself

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.