I have a custom array in TypeScript that needs to be filtered based on the city and job, with case-insensitivity as a requirement.
array = [{ name: "Hardik", city: null, job: null },
{ name: "John", city: "Ahmedabad", job: "IT" },
{ name: "Margie", city: "Mumbai", job: "CA" },
{ name: "Creature", city: "Banglore", job: null },
{ name: "Smooth", city: null, job: null }];
In order to achieve this, I apply a filter while converting all values to lowercase to prevent errors when dealing with null columns.
this.filter = this.array.filter(i =>
i.job.toLowerCase().indexOf('ca') != -1 ||
i.city.toLowerCase().indexOf('ahmedabad') != -1
)
Despite the initial approach working for non-null columns, it produces incorrect results when dealing with null valued columns.
this.filter = this.array.filter(i =>
i["job"] != null ? i.job.toLowerCase().indexOf('ca') != -1 : false ||
i["city"] != null ? i.city.toLowerCase().indexOf('ahmedabad') != -1 : false
)
The current output is:
[ { "name": "Margie", "city": "Mumbai", "job": "CA" } ]
The expected output should be:
[{ name: "John", city: "Ahmedabad", job: "IT" },
{ name: "Margie", city: "Mumbai", job: "CA" }]
You can find a detailed breakdown at this link: https://stackblitz.com/edit/filter-with-tolowercase-and-null?file=src/app/app.component.ts