Home > Software engineering >  Filter list object to other list in Angular
Filter list object to other list in Angular

Time:11-30

I have a custom item:

export class PartsChildInfo {
   name: string;
   materialName: string;
   thickNess: number;
}

export class PartGroupInfo
{
   materialName: string;
   thickNess: number;
}

for example, i have a list item PartsChildInfo:

list : PartsChildInfo  = [
{ Name = "GA8-0608" , MaterialName = "SS"  , ThickNess = 1 };
{ Name = "05F1-051" , MaterialName = "SUS" , ThickNess = 2 };
{ Name = "2B73-002" , MaterialName = "AL"  , ThickNess = 3 };
{ Name = "01-20155" , MaterialName = "SS"  , ThickNess = 1 };
{ Name = "02MEG099" , MaterialName = "SUS" , ThickNess = 2 }; ]

i want to get the list as below with MaterialName,ThickNess the same from list :

testChildList : PartGroupInfo = [
{ MaterialName = "SS"  , ThickNess = 1 };
{ MaterialName = "SUS" , ThickNess = 2 };
{ MaterialName = "AL"  , ThickNess = 3 }; ]

i'm using Typescript Angular

i have tried this

testChildList : PartGroupInfo[] = [];
for (let i = 0; i < list.length; i  ) {
   let targeti = list[i];
   for (let j = 0; j < this.testChildList.length; j  ) {
      let targetj = this.testChildList[j];
      if (targeti.materialName != targetj.materialName && targeti.thickNess != targetj.thickNess) {
        let item = new PartGroupInfo();
        item.materialName = targeti.materialName;
        item.thickNess = targeti.thickNess;
        this.testChildList.push(item);
       }
    }
 }

but return list is null. how should i fix it?

CodePudding user response:

Perhaps use .forEach to iterate the list array, check the item is existed in testChildList via index. Push the item to testChildList when index is -1 (no existed).

this.list.forEach((item) => {
  var i = this.testChildList.findIndex(
    (x) =>
      x.materialName == item.materialName && x.thickNess == item.thickNess
  );

  if (i == -1)
    this.testChildList.push({
      materialName: item.materialName,
      thickNess: item.thickNess,
    });
});

Sample Solution on StackBlitz

  • Related