js如何判断数组里对象的value是否有重复

如果有重复,给有重复的对象里增加个key值 isRepeat: true
比如

[
  { value: 123, key:1 },
  { value: 111, key:2},
  { value: 123, key:3}
]

处理后是

[
  { value: 123, key:1, isRepeat: true },
  { value: 111, key:2 },
  { value: 123, key:3, isRepeat: true }
]

麻烦各位大佬了

阅读 6.5k
6 个回答
list.forEach((item, index) => {
    if(list.some(citem => citem !== item && citem.value === item.value)){
        item.isRepeat = true
    }
})

最大的问题应该是时间复杂度

const data = [
  { value: 123, key:1 },
  { value: 111, key:2},
  { value: 123, key:3}
]
data.reduce((store, item) => {
  if (store[item.value]) {
    store[item.value].isRepeat = item.isRepeat = true;
  } else {
    store[item.value] = item;
  }
  return store;
}, {})
console.log(data)
const bucket = {}
for (const [ key, item ] of arr.entries()) {
    if (item.value in bucket) arr[bucket[item.value]].isRepeat = item.isRepeat = true
    else bucket[item.value] = key
}
var obj = {}
arr.forEach(item => {
    if (obj[item.value]) {
        obj[item.value].isRepeat = true
        item.isRepeat = true
    } else {
        obj[item.value] = item
    }
})
const arr = [{
        value: 123,
        key: 1
    },
    {
        value: 111,
        key: 2
    },
    {
        value: 123,
        key: 3
    }
]

const valueMap = {};
arr.forEach((item, index) => {
    if (!valueMap[item.value]) valueMap[item.value] = new Array();
    valueMap[item.value].push(index);
});

for (let key in valueMap) {
    const values = valueMap[key];
    if (values.length < 2) continue;
    for (let i = 0; i < values.length; i++) {
        const index = values[i];
        arr[index].isRepeat = true;
    }
}
let arr = [
      { value: 123, key: 1 },
      { value: 111, key: 2 },
      { value: 123, key: 3 },
    ]

    let res = arr.reduce((acc, curr) => {
      let indexOf = acc.map(item => item.value).indexOf(curr.value)

      if (indexOf !== -1) {
        curr.isRepeat = true

        if (!acc[indexOf].isRepeat) {
          acc[indexOf].isRepeat = true
        }
      }
      acc.push(curr)

      return acc
    }, [])

    console.log(res);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏