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

Filtering by user role in js

I have following code.

    export default function App() {
      const users = [
    { id: 34, name: "A", role: "pro" },
    { id: 43, name: "B", role: "customer" },
    { id: 35, name: "C", role: "pro" },
    { id: 55, name: "D", role: "pro" },
    { id: 67, name: "test", role: "pro" },
    { id: 543, name: "Jhon", role: "customer" }
     ];

     const customer = users.filter((u) => {
      return u.role === "customer";
     });

     const pro = users.filter((u) => {
    return u.role === "pro";
     });

    return (
    <div className="App">
      <Card role={"Customer"} count={customer.length} />
      <Card role={"Pro"} count={pro.length} />
    </div>
    );
    }

I am trying to filter users by their role and then I am showing the count of that role in Card component.

For every role I am writing filter function. That is working, but how can I improve my code for not repeating myself ?

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

>Solution :

Maybe you can try creating one function which filters users by their role and returns an array of a particular user by role, here I tried you can take look into this.

import Card from "./Card";
import "./styles.css";

export default function App() {
  const users = [
    { id: 34, name: "A", role: "pro" },
    { id: 43, name: "B", role: "customer" },
    { id: 35, name: "C", role: "pro" },
    { id: 55, name: "D", role: "pro" },
    { id: 67, name: "test", role: "pro" },
    { id: 543, name: "Jhon", role: "customer" }
  ];

  const customer = checkUserByRole('customer');

  const pro = checkUserByRole('pro');

  function checkUserByRole(role) {
    const filteredUser  = users.filter((user) => {
      return user.role === role;
    });
    return filteredUser;
  }
  return (
    <div className="App">
      <Card role={"Customer"} count={customer.length} />
      <Card role={"Pro"} count={pro.length} />
    </div>
  );
}

}

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