如果有重复,给有重复的对象里增加个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 }
]
麻烦各位大佬了
如果有重复,给有重复的对象里增加个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 }
]
麻烦各位大佬了
最大的问题应该是时间复杂度
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);
27 回答13k 阅读
6 回答2.3k 阅读✓ 已解决
8 回答3.5k 阅读✓ 已解决
6 回答1.3k 阅读✓ 已解决
5 回答5.3k 阅读✓ 已解决
4 回答1.6k 阅读✓ 已解决
6 回答1.1k 阅读