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

Filter an object by value from array

I have an array of object b and an array a. I would like to filter b to only have objects where the to values are in a. I’ve tried many ways but I always receive an empty array. For example this case, the final result would be an array with the first and the second object from the array but not the last one.

const a = [
    "dfd302f4-571b-42da-9b35-07d1d9b6e68d",
    "d7099abd-6872-48db-bdd7-ca99e4513586",
    "93272093-5089-40cd-8c3d-2412377e1f32"
  ];

  const b = [
    {
      name: "toto",
      to: [
        "d7099abd-6872-48db-bdd7-ca99e4513586",
        "93272093-5089-40cd-8c3d-2412377e1f32"
      ]
    },
    { name: "tota", to: ["dfd302f4-571b-42da-9b35-07d1d9b6e68d"] },
    { name: "tota", to: ["8418v4rfe484evf48ez64vrfe6zv4r8ezvf4"] }
  ];

  console.log(b.filter(user => a.includes(user.to)))

>Solution :

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

Need to check array with array (use some and includes)

const a = [
  "dfd302f4-571b-42da-9b35-07d1d9b6e68d",
  "d7099abd-6872-48db-bdd7-ca99e4513586",
  "93272093-5089-40cd-8c3d-2412377e1f32",
];

const b = [
  {
    name: "toto",
    to: [
      "d7099abd-6872-48db-bdd7-ca99e4513586",
      "93272093-5089-40cd-8c3d-2412377e1f32",
    ],
  },
  { name: "tota", to: ["dfd302f4-571b-42da-9b35-07d1d9b6e68d"] },
  { name: "tota", to: ["8418v4rfe484evf48ez64vrfe6zv4r8ezvf4"] },
];

console.log(b.filter(({ to }) => to.some((item) => a.includes(item))));
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