Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using a forEach inside a filter to organize data

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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..

>Solution :

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)),
      
    );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading