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

How in JS to filter a value on a condition from a map

const statuses = [
  "PENDING_SITE",
  "CONSENTED",
  "PENDING_CALL",
  "PENDING_SATTUS"
];

const disqualificationReasons = [
  {
    value: "personal",
    message: "Personal"
  },
  {
    value: "no_nearby_site",
    message: "No nearby site"
  },
  {
    value: "ineligible",
    message: "Ineligible"
  },
  {
    value: "no_contact",
    message: " No contact"
  },
  {
    value: "screen_failure",
    message: "Screen failure"
  },
  { value: "other", message: "Other" }
];

const result = disqualificationReasons.map(({ message, value }) => ({
  message
}));

console.log(result.map((x) => x.message));

document.getElementById("app").innerHTML = `
  <div>${result.map((x) => x.message)}</div>
  <div>${result
    .filter((value) => value === "screen_failure")
    .map((x) => x.message)}</div>
`;
<!DOCTYPE html>
<html>

<head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
</head>

<body>
    <div id="app"></div>

    <script src="src/index.js">
    </script>
</body>

</html>

The issue I’m having is that

I have an array of obj the one called disqualificationReasons and I’m mapping those in reality to a dropdown menu.

I need to populate the dropdown with the messages but I need to filter when I have statuses as ‘CONSENTED’ and ‘PENDING_SITE’

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

When I have ‘CONSENTED’ OR ‘PENDING_SITE’ statuses I see all the messages in the menu.

When I’m not in ‘CONSENTED’ or ‘PENDING_SITE’ the message ‘Screen failure’ should not be displayed.

I tried to use the filter but got stuck on how to do it.

Pratically based of what the status is on above I have to show all messages or ide the one message ‘Screen failure’.

>Solution :

I’m not sure if this is what you’re looking for, but take a look:

const status = "";
const result = disqualificationReasons.filter((e) => {
  if (status === "CONSENTED" || status === "PENDING_SITE") return true;

  return e.value !== "screen_failure";
});

In the status you will set one of your statuses. If the status is set to CONSENTED or PENDING_SITE then the screen_failure message will be shown in the array. If it’s not one of those two statuses then the screen_failure will be removed from the array.

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