Search code examples
javascriptarraysduplicatesfiltering

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:

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)