Search code examples
javascriptangulartypescriptangular8

Filter array of objects based on multiple conditions Angular 8


I am getting below response, i wanted to filter array of objects based on lineId and subFamily and status.

i tried below code and it is working fine for lineId Filter, but i need to add one more condition for subFamilyId.

I wanted to check 2 below conditions

1) If lineId is same but subfamily is different than push both the Object. For ex - in the above response, two same object with lineId 2 but subFamily is different so need to keep both objects

2) if lineId is same but status is different for ex New and Submitted status, than keep submitted status Object. For ex - In the above response, two same object with subfamily 03 and lineId 3, but their status is different, so wanted to push submitted status object only.

Can anyone help me to apply one more condition for subFamily Id in the above code

Below is the Response

const data = [
    {
        "Subfamily": "01",
        "lineId": "2",
        "status": "Submitted"
    },
    {
        "Subfamily": "02",
        "lineId": "2",
        "status": "Submitted"
    },
    {
        "Subfamily": "03",
        "lineId": "3",
        "status": "Submitted"
    },
    {
        "Subfamily": "03",
        "lineId": "3",
        "status": "New"
    },
    {
        "Subfamily": "04",
        "lineId": "4",
        "status": "New"
    }
];

Expected Output

output  = [
    {
        "Subfamily": "01",
        "lineId": "2",
        "status": "Submitted"
    },
    {
        "Subfamily": "02",
        "lineId": "2",
        "status": "Submitted"
    },
    {
        "Subfamily": "03",
        "lineId": "3",
        "status": "Submitted"
    },
    {
        "Subfamily": "04",
        "lineId": "4",
        "status": "New"
    }
];

Below is my working code

 removeDuplicatesObject(data){
    const uniqueResponse = data.reduce((acc, item) => {
      if (!acc[item.lineId] || item.status === "Submitted") {
        acc[item.lineId] = item;
      }
      return acc;
    }, {});
    const uniqueResponseArray = Object.values(uniqueResponse);
    return uniqueResponseArray;
  }

I appreciate any help on this.


Solution

  • You could group by Subfamily/lineId and keep objects with status: "Submitted".

    const
        data = [{ Subfamily: "01", lineId: "2", status: "Submitted" }, { Subfamily: "02", lineId: "2", status: "Submitted" }, { Subfamily: "03", lineId: "3", status: "Submitted" }, { Subfamily: "03", lineId: "3", status: "New" }, { Subfamily: "04", lineId: "4", status: "New" }],
        result = Object.values(data.reduce((r, o) => {
            const key = ['Subfamily', 'lineId'].map(k => o[k]).join('|');
            if (!r[key] || o.status === 'Submitted') r[key] = o;
            return r;
        }, {}));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }