Home > other >  How to filter array of object based on another array Angular 8
How to filter array of object based on another array Angular 8

Time:07-21

I have below sample data in excelData and apiResponse.

I want to filter excelData array based on apiResponse makeLineName.

For Ex - In apiResponse, we have below TestDemo1 and Test565 makeLineName available So i want to search exceldata array for this TestDemo1 and Test565 makeLineName and if same name availalble in excelData than filter the excelData array and remove this object from excelData array of object and provide the rest object in result.

const excelData = [
      {
        makeLineId: 25,
        makeLineName: "TestDemo1",
        makeProcessTypeId: 43
      },
      {
        makeLineId: 26,
        makeLineName: "Test565",
        makeProcessTypeId: 44
      },
      {
        makeLineId: 27,
        makeLineName: "Luck",
        makeProcessTypeId: 45
      }
    ];

    const apiResponse = [
      {
        makeLineId: 25,
        makeLineName: "TestDemo1",
        makeProcessTypeId: 43
      },
      {
        makeLineId: 26,
        makeLineName: "Test565",
        makeProcessTypeId: 44
      }
    ];

Expected output

const excelData = [      
      {
        makeLineId: 27,
        makeLineName: "Luck",
        makeProcessTypeId: 45
      }
    ];

CodePudding user response:

Array.map and Array.filter

You can look through the apiResponse to get each element. Here I have used map to loop through apiResponse.

Then you can filter the data in excelData using filter that returns the elements from the given array that pass the test implemented by the provided function.

let excelData = [ { makeLineId: 25, makeLineName: "TestDemo1", makeProcessTypeId: 43 }, { makeLineId: 26, makeLineName: "Test565", makeProcessTypeId: 44 }, { makeLineId: 27, makeLineName: "Luck", makeProcessTypeId: 45 } ];
const apiResponse = [ { makeLineId: 25, makeLineName: "TestDemo1", makeProcessTypeId: 43 }, { makeLineId: 26, makeLineName: "Test565", makeProcessTypeId: 44 } ];


const filteredData=excelData.filter(x=>!apiResponse.find(e=>e.makeLineId==x.makeLineId))

console.log(filteredData);

  • Related