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

JavaScript实现:排除指定ID,递增值至无重复属性值

问题需求

现有对象数组arrList与参数checkId,需实现以下逻辑:

  • 若数组中存在value重复且id不等于checkId的对象,需递增该对象的value
  • 递归执行此操作,直至数组中除指定ID的对象外,无重复的value

尝试的代码
const arrList = [
  { id: 11, value: null },
  { id: 14, value: 4 },
  { id: 28, value: 1 }, // 需要改为 2
  { id: 26, value: 3 },
  { id: 78, value: 1 }, 
  { id: 21, value: 6 },
  { id: 24, value: 8 }
];
const checkId = 78;

for (const res of arrList) {
  const duplicates = hasDuplicates(res, arrList);
  res.value = (res.id !== checkId && res.value >= duplicates.value)
    ? (res.value || 0) + 1
    : res.value;
}

console.log(arrList);

function hasDuplicates(item, list) {
  return list.find(e => e.value === item.value);
}

预期结果
[
  { id: 11, value: null },
  { id: 14, value: 4 },
  { id: 28, value: 2 },
  { id: 26, value: 3 },
  { id: 78, value: 1 },
  { id: 21, value: 6 },
  { id: 24, value: 8 }
]

问题分析与解决方案

原代码存在的问题

  1. 未区分指定ID对象:hasDuplicates函数仅查找相同value的元素,未排除checkId对应的对象,可能误修改指定对象的value
  2. 仅执行一次检查:原代码只遍历数组一次,递增后的value若再次和其他元素重复,无法继续处理,不符合"递归执行直至无重复"的要求
  3. 逻辑判断错误:res.value >= duplicates.value的条件不合理,只要存在重复(且当前对象不是指定ID)就需要递增,无需比较大小

修正后的代码

const arrList = [
  { id: 11, value: null },
  { id: 14, value: 4 },
  { id: 28, value: 1 },
  { id: 26, value: 3 },
  { id: 78, value: 1 },
  { id: 21, value: 6 },
  { id: 24, value: 8 }
];
const checkId = 78;

// 收集已使用的value,先加入指定ID对象的value
const usedValues = new Set();
const targetItem = arrList.find(item => item.id === checkId);
if (targetItem?.value !== null) {
  usedValues.add(targetItem.value);
}

// 遍历处理每个非指定ID的对象
arrList.forEach(item => {
  if (item.id === checkId || item.value === null) return;

  let currentValue = item.value;
  // 循环递增直到当前value不在已使用集合中
  while (usedValues.has(currentValue)) {
    currentValue++;
  }
  // 更新对象value并加入集合
  item.value = currentValue;
  usedValues.add(currentValue);
});

console.log(arrList);

代码逻辑说明

  1. 创建Set记录已占用的value,先将checkId对应对象的value加入集合(若value不为null)
  2. 遍历数组中的每个对象:
    • 若为checkId对应的对象或value为null,直接跳过
    • 对其他对象,从当前value开始循环检查,若value已被占用则递增,直到找到未使用的value
    • 更新对象的value,并将新value加入已使用集合
  3. 最终数组中除指定ID对象外,所有value均唯一

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 22:38:25