筛选器列表-逻辑问题

时间:2019-05-01 12:15:56

标签: angular typescript

我需要找到以下2个列表的匹配记录。

我有一个名为allAnimals的列表:Animal和另一个名为domesticAnimals的列表:Animal

现在,我需要在2个列表之间进行比较,并返回一个animalId相等的列表。

    const commonList = this.allAnimals.filter(item1 => 
      this.domesticAnimals.find(item2 => item1.animalId=== item2.animalId)); 

      console.log("common anumal count is "+ commonList.length);

当我打印计数时,它给出的是allAnimals而不是commonList的计数。我该如何解决?

**Animal Model**

animalId
animalName
animalAge

allAnimals

[{"animalId":1 , "animalName":"elephant"},
{"animalId":2 , "animalName":"elephant1"},
{"animalId":3 , "animalName":"ant"}]

domesticAnimals

[{"animalId":2 , "animalName":"elephant1"}]

2 个答案:

答案 0 :(得分:2)

您的逻辑是正确的。见下文:

const myAnimals = ['Donkey', 'Moose', 'Cat', 'Dog'];
const domesticAnimals = ['Cat', 'Dog', 'Bunny', 'Lizard', 'Goldfish'];

const myDomesticAnimals = myAnimals.filter(
  myAnimal => domesticAnimals.find(
    domesticAnimal => domesticAnimal === myAnimal
  )
);

console.log(myDomesticAnimals);

/*  Expected Output (the intersection of the two lists):

  [
    "Cat",
    "Dog"
  ]

*/

您的两个数组可能包含相同的元素,因此过滤器并没有减少任何大小。

编辑

提供您提供的数据:

const allAnimals = [
  {
    "animalId": 1,
    "animalName": "elephnat"
  },
  {
    "animalId": 2,
    "animalName": "elephnat1"
  },
  {
    "animalId": 3,
    "animalName": "ant"
  }
];

const domesticAnimals = [{
  "animalId": 2,
  "animalName": "elephnat1"
}];

const allDomesticAnimals = allAnimals.filter(
  animal => domesticAnimals.find(
    domesticAnimal => domesticAnimal.animalId === animal.animalId
  )
);

console.log(allDomesticAnimals);

/*  Expected Output (the intersection of the two lists):

  [
    {
      "animalId": 2,
      "animalName": "elephnat1"
    }
  ]

*/

答案 1 :(得分:1)

尝试以下操作: *单行代码,希望您喜欢这个!!

 const result = allAnimals.filter(item => domesticAnimals.some(entry => entry.animalId == item.animalId));