I am trying to filter through a large set of data that has an array nested inside whos values I need to compare against a string. To compare them I need to clean the strings because its coming through user input and spacing/capitalization may vary. So I had my functions working through a filter that looked like this
data initially looked like
formularyOptions = [{Condition: "headache"...}{Condition: "hair loss"..}...]
chiefComplaint = "Headache"
const cleanText = (value) => {
let str = value;
if (!str) {
return value;
}
str = str.toLowerCase();
str = str.replace(/\s/g, "");
return str;
};
let formularyList = formularyOptions.filter(
(item) => !!chiefComplaint && cleanText(item.Condition) === cleanText(chiefComplaint),
);
And this worked just fine but now
My data looks like this:
[{Condition: ["headache", "migraine"]...}{Condition: ["hair loss"]..}...]
Ive tried changing my filter to loop through the Conditions array but that doesnt return anything for some reason I dont understand. And the includes method wont work since it is case sensitive. Any advice on how to approach this or even why a forEach wouldnt work inside a .filter would be super helpful this is my attempt with a for loop:
let formularyList = formularyOptions.filter(
(item) => !!chiefComplaint && item.Condition.forEach((condition) => cleanText(condition) === cleanText(chiefComplaint)),
);
which just returns an empty array..
CodePudding user response:
You are including a .forEach(...)
inside a boolean conditional, but it is void, it only loops, nothing is returnted.
I think you actually need to use the .some(...)
instead, which will try to find some item that corresponds to the condition:
let formularyList = formularyOptions.filter(
(item) => !!chiefComplaint && item.Condition.some((condition) => cleanText(condition) === cleanText(chiefComplaint)),
);