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

如何过滤对象数组:保留指定类别单条记录其余类别完整保留

解决方案

嘿,这需求很好实现!我给你准备了两种方式,一种是专门针对你现在要处理Category2的场景,另一种是更通用的版本,方便以后你要给其他类别也设置类似规则。

针对Category2的特定实现

这个方式简单直接,专门匹配你当前的需求:

const obj = [
  {category: "Category", value: 1},
  {category: "Category", value: 2},
  {category: "Category", value: 3},
  {category: "Category1", value: 1},
  {category: "Category1", value: 2},
  {category: "Category1", value: 3},
  {category: "Category2", value: 1},
  {category: "Category2", value: 2},
  {category: "Category2", value: 3},
];

// 标记是否已经保留过Category2的第一条记录
let hasKeptCategory2 = false;

const filteredObj = obj.filter(item => {
  // 处理Category2的情况
  if (item.category === "Category2") {
    if (!hasKeptCategory2) {
      hasKeptCategory2 = true;
      return true; // 保留第一条
    }
    return false; // 过滤后续的Category2条目
  }
  // 其他类别全部保留
  return true;
});

console.log(filteredObj);

代码解释

  • 我们用一个布尔变量hasKeptCategory2来跟踪是否已经保留了Category2的第一条数据。
  • 遍历数组时,遇到Category2的条目,只有当还没保留过的时候才放行,同时把标记设为true,后续的同类别条目就会被过滤掉。
  • 其他类别的条目直接全部保留,完全不影响原有记录。

可扩展的通用实现

如果以后你需要给多个类别设置“只保留第一条”的规则,用这个版本更灵活:

const obj = [
  {category: "Category", value: 1},
  {category: "Category", value: 2},
  {category: "Category", value: 3},
  {category: "Category1", value: 1},
  {category: "Category1", value: 2},
  {category: "Category1", value: 3},
  {category: "Category2", value: 1},
  {category: "Category2", value: 2},
  {category: "Category2", value: 3},
];

// 定义需要只保留第一条的类别集合
const keepOnlyFirstCategories = new Set(["Category2"]);
// 记录已经保留过第一条的类别
const keptCategories = new Set();

const filteredObj = obj.filter(item => {
  const category = item.category;
  if (keepOnlyFirstCategories.has(category)) {
    if (!keptCategories.has(category)) {
      keptCategories.add(category);
      return true;
    }
    return false;
  }
  return true;
});

console.log(filteredObj);

代码解释

  • 用keepOnlyFirstCategories这个Set来存储所有需要“只保留第一条”的类别,以后要加新类别直接往里面加就行,比如keepOnlyFirstCategories.add("Category3")。
  • keptCategories用来记录哪些类别的第一条已经被保留过,避免重复保留。
  • 逻辑和之前类似,但扩展性更强,适合多类别场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 14:07:31