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 array of objects with same id, but different value in other key

I’m having an array of objects with keys Id and type. I’m trying to filter for duplicate with the same id but different type, if id is the same and different type, I’d like to keep the type HD and filtered out the one with type SD, I’ve tried nested filter and findIndex, but that didn’t work. I’m kinda stuck on the filtering logic.

Attempted:

const filteredArr = arr.filter((a, index, tmp) => tmp.findIndex(b => a.id === b.id ? b.type === “HD”) === index);

Array:

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

const arr = [
    {
        id: "123",
        type: "HD",
    },
    {
        id: "123",
        type: "SD",
    },
    {
        id: "1234",
        type: "HD",
    },
    {
        id: "12",
        type: "SD",
    },
];

Can you guys please suggest a solution for filtering this array. Thanks for your help in advance.

>Solution :

Here’s an approach using reduce, we create a map with id as key and value as each item. If same id is seen again and type is not "HD" we override the current value.

const arr=[{id:"123",type:"HD"},{id:"123",type:"SD"},{id:"1234",type:"HD"},{id:"12",type:"SD"}];

const unique = Object.values(
  arr.reduce((acc, curr) => {
    if (!acc[curr.id] || acc[curr.id].type !== "HD") {
      acc[curr.id] = curr;
    }
    return acc;
  }, {})
);

console.log(unique)
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