You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript/TypeScript过滤JSON数组,保留仅存于第一个数组的对象

解决数组过滤问题:移除存在于第二个数组中的对象

你的问题根源

先看看你原来的嵌套循环为什么出错:
你现在的逻辑是只要当前student的id和某一个emp的id不匹配,就把这个student加入结果数组,这会导致同一个student被多次添加(比如id=2的student会和emp里的3个对象都不匹配,所以被push3次)。这显然不是你想要的结果。

再看你项目里的filter代码:this.typesData.includes(this.typesData[index].appointmentType.id),includes只能检查数组中是否包含原始值,但this.typesData是对象数组,所以这个判断永远不会生效,你需要用some来检查是否存在匹配的对象属性。


正确的解决方案

方法1:高效的Set+Filter(推荐,大数据量更优)

先把第二个数组的id提取到Set中(Set.has()是O(1)时间复杂度,比遍历数组快很多),再用filter过滤第一个数组:

var students = [{id: 1, name : 'SSS'}, {id: 2, name : 'SSa'}, {id: 3, name : 'SSb'}, {id: 4, name : 'SSc'}, {id: 5, name : 'SSd'}]; 
var emp = [{id: 1, name : 'SSS'}, {id: 4, name : 'SSc'}, {id: 5, name : 'SSd'}];

// 提取emp的id到Set
const empIds = new Set(emp.map(item => item.id));
// 过滤students,保留不在emp中的对象
const finalarr = students.filter(student => !empIds.has(student.id));

console.log(finalarr);
// 输出:[{id: 2, name : 'SSa'}, {id: 3, name : 'SSb'}]

方法2:Filter+Some(无需额外数据结构)

如果数组不大,直接用filter配合some检查是否存在匹配的id:

const finalarr = students.filter(student => 
  // 检查emp中是否没有和当前student.id匹配的对象
  !emp.some(empItem => empItem.id === student.id)
);

方法3:修正你的嵌套循环

如果你想保留循环的写法,需要先判断当前student是否在emp中存在,只有不存在时才加入结果:

var finalarr = [];
for (let i = 0; i < students.length; i++) { 
  let isExist = false;
  for (let j = 0; j < emp.length; j++) { 
    if (students[i].id === emp[j].id) { 
      isExist = true;
      break; // 找到匹配就跳出循环,提升效率
    } 
  }
  if (!isExist) {
    finalarr.push(students[i]);
  }
} 
console.log(finalarr);

你的项目代码修正

针对你项目里的这段代码:

this.appointmentTypes.filter((data, index) => this.typesData.includes(this.typesData[index].appointmentType.id))

修正为(用Set优化版):

// 先提取typesData中所有appointmentType的id
const typeIds = new Set(this.typesData.map(item => item.appointmentType.id));
// 过滤appointmentTypes,保留不在typesData中的类型
const filteredAppointmentTypes = this.appointmentTypes.filter(type => 
  !typeIds.has(type.id)
);

或者用Some的版本:

const filteredAppointmentTypes = this.appointmentTypes.filter(apptType => 
  !this.typesData.some(data => data.appointmentType.id === apptType.id)
);

内容的提问来源于stack exchange,提问作者Santhosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:36:09