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

BlankSpace
  • 49

如果有重复,给有重复的对象里增加个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 }
]

麻烦各位大佬了

回复
阅读 2.7k
5 个回答
✓ 已被采纳
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)
ForkKILLET
  • 2.5k
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
}
林学开
  • 2
新手上路,请多包涵
var obj = {}
arr.forEach(item => {
    if (obj[item.value]) {
        obj[item.value].isRepeat = true
        item.isRepeat = true
    } else {
        obj[item.value] = item
    }
})
慢条斯理的小可
  • 2
新手上路,请多包涵
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;
    }
}
宣传栏