比较2个数组以在Angular中创建第3个公共项数组

时间:2019-03-05 21:48:01

标签: arrays angular typescript

我试图找出TypeScript逻辑来比较2个数组并创建所有常见项目的第3个数组。

employees: any;
  offices: any;
  constructor() {
    this.employees = [
      { fname: "John", lname: "James", state: "New York" },
      { fname: "John", lname: "Booth", state: "Nebraska" },
      { fname: "Steve", lname: "Smith", state: "Nebraska" },
      { fname: "Stephanie", lname: "Smith", state: "New Hampshire" },
      { fname: "Bill", lname: "Kydd", state: "New Mexico" },
      { fname: "Bill", lname: "Cody", state: "Wyoming" }
    ]

    this.offices = [
      { state: "New York", city: "Albany" },
      { state: "Nebraska", city: "Omaha" },
      { state: "New Mexico", city: "Albuquerque" },
      { state: "New Hamshire", city: "Manchester" },
      { state: "California", city: "Redding" }
    ]
let finalOffice = this.employees.filter((state: any) => !this.offices.include(state));
console.log(finalOffice);

}

理想情况下,第三个数组是这样的:

empofclist = [
  {state: "New York", city: "Albany", fname: "John",lname: "James"},
  {state: "Nebraska", city: "Omaha",fname: "John",lname: "Booth"},
  {state: "Nebraska", city: "Omaha",fname: "Steve",lname: "Smith"},
  {state: "New Mexico", city: "Albuquerque",fname: "Bill",lname: "Kydd"},
  {state: "New Hamshire",city: "Manchester",fname: "Stephanie",lname: "Smith"}
]

请注意,有一个内布拉斯加州的副本,每个人一个,而且没有加州的清单,因为那里没有雇员,也没有比尔·科迪的清单,因为怀俄明州没有办事处。

关于在哪里可以找到相关信息的任何建议?

1 个答案:

答案 0 :(得分:0)

            this.employees = [
                  { fname: "John", lname: "James", state: "New York" },
                  { fname: "John", lname: "Booth", state: "Nebraska" },
                  { fname: "Steve", lname: "Smith", state: "Nebraska" },
                  { fname: "Stephanie", lname: "Smith", state: "New Hampshire" },
                  { fname: "Bill", lname: "Kydd", state: "New Mexico" },
                  { fname: "Bill", lname: "Cody", state: "Wyoming" }
            ];


            this.offices = [
                  { state: "New York", city: "Albany" },
                  { state: "Nebraska", city: "Omaha" },
                  { state: "New Mexico", city: "Albuquerque" },
                  { state: "New Hampshire", city: "Manchester" },
                  { state: "California", city: "Redding" }
            ]

            let finalArr = [];
            let self = this;
            for (let g=0;g<self.employees.length;g++) {
                    for (let h=0;h<self.offices.length;h++) {
                            if (self.employees[g]['state'] === self.offices[h]['state']) {
                                    finalArr.push(self.employees[g]);
                                    finalArr[finalArr.length - 1]['city'] = self.offices[h]['city'];
                                    break;
                            }
                    }
            }

console.log(finalArr);

您可以尝试这样的事情。