我想在javascript中找到一个重复的数字和它在对象数组中的名称。
我检查了相关问题但没有帮助找到确切的重复计数。如果有多个重复项,即使他们也不专注于找到它
我尝试了这个,它将在查找重复项时抛出消息。但是我想要重复计数并处理多个重复项的情况,每个名称的计数多次出现。
我的代码:
true
数组可能是这样的:
public static void main(String[] args) {
while (each object in people[] != true) { // This obviously wouldn't
// work but is the closest I
// can get.
object.loadPeople();
object.moveElevator();
object.unloadPeople();
}
}
我想要一条消息,例如“name1重复发生2次”和“name2重复发生3次”
答案 0 :(得分:1)
您可以只计算对象中的名称。
var array = [{ name: "name1", value: "value1" }, { name: "name2", value: "value2" }, { name: "name1", value: "value42" }, { name: "name2", value: "value52" }, { name: "name3", value: "value2" }, { name: "name2", value: "value2" }],
count = Object.create(null);
array.forEach(function (o) {
count[o.name] = (count[o.name] || 0) + 1;
});
Object.keys(count).forEach(function (k) {
if (count[k] > 1) {
console.log(k + ' is duplicate occuring ' + count[k] + ' times.');
}
});
console.log(count);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
这将列出您的副本:
let array=[
{"name":"name1","value":"value1"},
{"name":"name2","value":"value2"},
{"name":"name1","value":"value42"},
{"name":"name2","value":"value52"},
{"name":"name3","value":"value2"},
{"name":"name2","value":"value2"}];
const counts = array.reduce((accum, current) => {
accum[current.name] = (accum[current.name] || 0) + 1;
return accum;
}, {});
Object.keys(counts)
.filter(key => counts[key] > 1)
.forEach(grp => console.log(`${grp} is duplicate occurring ${counts[grp]} times`));