Search code examples
javascripttypescriptangular-filters

Typescript filter two array of objects


I have to objects where I need to filter out the data that exists in one but not the other

For example Object 1

0:Object {Name: "Java", ResourceCount: 3}
1:Object {Name: "DotNet", ResourceCount: 4}
2:Object {Name: "Hadoop", ResourceCount: 1}
3:Object {Name: "Pega", ResourceCount: 2}
4:Object {Name: "Oracle", ResourceCount: 1}
5:Object {Name: "ETL", ResourceCount: 1}

Object 2

0:"DotNet"
1:"ETL"
2:"Hadoop"
3:"Java"
4:"Oracle"
5:"Pega"
6:"Mainframe"

I need to return "MainFrame" from object 2 since it does not exist in object 1.

This is what I have tried so far to no avail.

  const filteredList = object2.filter(item1 => 
          object1.find(item2 => item1.Name != item2.Name));

all this does is return all of the rows in object 2


Solution

  • Basically, create an array of names to help filter the object2; (array2) I have joined the results with a , if multiple names exist

    let object1 = [{Name: "Java", ResourceCount: 3}, {Name: "DotNet", ResourceCount: 4}, {Name: "Hadoop", ResourceCount: 1}, {Name: "Pega", ResourceCount: 2}, {Name: "Oracle", ResourceCount: 1}, {Name: "ETL", ResourceCount: 1}]
    let object2 = ["DotNet", "ETL", "Hadoop", "Java", "Oracle", "Pega", "Mainframe"]
    
    let object1Names = object1.map(obj => obj.Name); // for caching the result
    results = object2.filter(name => !object1Names.includes(name)).join(',');
    console.log(results);