admin管理员组文章数量:1431705
Given the following object:
answers = {'a': 3,'b': 2,'c': 3, 'd': 1};
How can I find whether or not there is a duplicate value? I need to write a condition that will say if two of these have the same value, then console.log('duplicate values found')
.
Given the following object:
answers = {'a': 3,'b': 2,'c': 3, 'd': 1};
How can I find whether or not there is a duplicate value? I need to write a condition that will say if two of these have the same value, then console.log('duplicate values found')
.
- 2 Objects can't have duplicate keys. – Mike Cluck Commented Mar 2, 2016 at 17:49
- Yes, I am aware. I'm looking for a test that will return whether or not there are duplicate values in there. – Pdnell Commented Mar 2, 2016 at 17:51
- Can the values themselves be objects etc.? – user663031 Commented Mar 3, 2016 at 10:30
2 Answers
Reset to default 3You have to write a nested loop to find that,
var keys = Object.keys(answers);
var dupe = false;
for(var i=0;i<keys.length;i++){
for(var j=i+1;j<keys.length;j++){
if(answers[keys[i]] === answers[keys[j]]){
dupe = true;
break;
}
}
if(dupe){ console.log("dupe value is there.."); break; }
}
DEMO
I guess you mean duplicate values and not duplicate key/value pairs. This is how I'd do it:
function findDuplicateValues(input) {
var values = {},
key;
for (key in input) {
if (input.hasOwnProperty(key)) {
values[input[key]] = values.hasOwnProperty(input[key]) ? values[input[key]] + 1 : 1;
}
}
for (key in values) {
if (values.hasOwnProperty(key) && values[key] > 1) {
console.log('duplicate values found');
break;
}
}
}
For large objects it will be quicker than the previous answer, because there are no nested loops (this will execute in linear O(n) time rather than quadratic O(n2) time).
本文标签: Find duplicate value in JavaScript objectStack Overflow
版权声明:本文标题:Find duplicate value in JavaScript object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745587215a2664981.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论