有一个像下面这样的键值对
var point = [];
point["I1"] = 1000;
point["I2"] = 2000;
point["I3"] = 1000;
point["I4"] = 5000;
point["I5"] = 2000;
point["I6"] = 4000;
要查找重复值,结果哈希应仅包含重复值信息。
result["1000"] = " I1,I3";
result["2000"] = "I2,I5";
重复值应该是结果哈希的键。
我对数组进行了排序,但不知道遍历哈希来检查重复值以构建结果哈希
最佳答案
您可以使用点键循环检查所有值。
我稍微改变了你的条件。您可以为 Array
设置额外的键但你最好使用 Object
反而。
每个值的结果将是一个数组,只需使用 toString
即可将其转换为逗号分隔值。调用每个数组。
编辑
根据要求编辑,包含only duplicates
您可以再次循环(但这次是在 hash
上)并得到不止一个结果。
var point = {
I1: 1000,
I2: 2000,
I3: 1000,
I4: 5000,
I5: 2000,
I6: 4000,
};
var hash = Object.create(null);
var result = Object.create(null);
Object.keys(point).forEach(k => {
var grp = point[k];
(grp in hash) ? hash[grp].push(k): (hash[grp] = [k]);
});
for (key in hash)
if (hash[key].length > 1)
result[key] = hash[key].toString();
console.log(hash['1000'].toString());
console.log(hash);
console.log(result);
关于javascript - 在 javascript 关联数组(哈希)中查找重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38508640/