使用Javascript从两个对象数组中删除重复项

时间:2019-11-05 09:33:52

标签: javascript

我有两个数组变量

let itSchool = [
  {
    'school': 'HS-1',
    'teachers': [
      {
        'name': 'John'
      },
      {
        'name': 'Eddy'
      }
    ]
  },
  {
    'school': 'HS-2',
    'teachers': [
      {
        'name': 'Edward'
      },
      {
        'name': 'John'
      }
    ]
  }
]

let itAbsence = [
  {
    'school': 'HS-1',
    'teacher': 'John'
  },
  {
    'school': 'HS-2',
    'teacher': 'Edward'
  }
]

如何通过与itSchool进行比较来删除相同名称的itAbsence?结果变为:

itSchool = [
  {
    'school': 'HS-1',
    'teachers': [
      {
        'name': 'Eddy'
      }
    ]
  },
  {
    'school': 'HS-2',
    'teachers': [
      {
        'name': 'John'
      }
    ]
  }
]

3 个答案:

答案 0 :(得分:2)

一线解决方案

const itSchool = [
  {
    "school": "HS-1",
    "teachers": [
      {
        "name": "John"
      },
      {
        "name": "Eddy"
      }
    ]
  },
  {
    "school": "HS-2",
    "teachers": [
      {
        "name": "Edward"
      },
      {
        "name": "John"
      }
    ]
  }
]

const itAbsence = [
  {
    "school": "HS-1",
    "teachers": "John"
  },
  {
    "school": "HS-2",
    "teachers": "Edward"
  }
]


const output = itSchool.map(s => ({...s, teachers: s.teachers.filter(ss => ss.name !== (itAbsence.find(i => i.school === s.school).teachers))  }))


console.log(output)

答案 1 :(得分:0)

itAbsent.forEach( absent => {
  let index = itSchool.findIndex( schoolVar => absent.school === schoolVar.school );
  if( index === -1 ) return;
  let teacherIndex = itSchool[index].teachers.findIndex( teacher => teacher.name === absent.teacher );
  if(teacherIndex != -1) itSchool[index].teachers.splice(teacherIndex, 1);
}

所以,这是一个基本逻辑:

  1. itAbsent上重复

  2. 对于其中的每个对象,在itSchool中找到匹配学校的索引。

  3. 在该学校的teachers数组中找到缺席的老师的索引。

  4. 通过array.splice()删除必要的老师。

请注意以下几点:

  1. 这仅在每所学校缺席一位老师时才有效。如果还有更多内容,则它们必须位于itAbsent数组中的不同对象上。

  2. 如果在itSchool中找不到学校或缺席的老师,函数将不执行任何操作(只是跳过它)。

  3. splice方法从字面上更改了我们正在唤醒的相同数组,例如itSchool[index].teachers。如果您不想更改它,则必须创建它的副本并将该副本传递给此代码以进行更改。

答案 2 :(得分:0)

我已经解决了

let newSchool = itSchool
itAbsence.map(rA => {
  itSchool.map(rS => {
    for (const [k, v] of rS.teachers.entries()) {
      if (v.name == rA.teacher) {
        rS.teachers.shift()
      }
    }
    return rS
  })
  newSchool = itSchool
})

console.log('itSchool = ', itSchool)