我有以下对象:
var data = {
2: [[1,2],[3,4,5],[6,7]],
3: [[1,2],[3,4],[6,7]],
4: [[1,2],[3,4,5],[6,7]],
5: [[10,2],[3,4,5],[60,7]]
}
我想从对象中获取密钥2
,因为它的值在数组中是重复的。可能有多个这样的重复键。
我使用lodash并尝试以下但它不会工作。我不知道如何开始:
var dups = [];
_.map(formData,function(key, value){
dups.push(value);
})
var duplicateArray = _.uniqWith(dups, _.isEqual);
答案 0 :(得分:1)
这段代码将匹配整个数组,而不管值序列和值计数。请考虑以下示例
//代码在这里
Plunker:https://plnkr.co/edit/6jEByZHQhcwUopqqG4a2?p=preview (单击上面的链接并打开控制台以查看结果)
这将输出[“2”,“3”]因为“2”matches
“4”和“3”matches
“6”。
//代码在这里
var data = {
2: [ [1, 2], [3, 4, 5], [6, 7]],
3: [[1, 2],[3, 4],[6, 7]],
4: [[2, 1, 2, 1],[5, 3, 4],[6, 7]],
5: [[10, 2],[3, 4, 5],[60, 7]],
6: [[2, 1],[3, 4],[7, 6, 6]]
}
var dups = [];
//sorted and uniq buffer.
var buff = _.clone(data);
_.forEach(buff, function(lvl1, key) {
buff[key] = _.map(lvl1, function(val) {
return _.uniq(_.sortBy(val));
});
});
_.forEach(buff, function(lvl1, key) {
//Match each row with all others.
//i.e. 2 with 3, 2 with 4, 2 with 5 ..... 6 with 5.
_.forEach(buff, function(_lvl1, _key) {
//Skip entries like 2 with 2, 3 with 3 and so on
if (key !== _key) {
console.log('compare ' + key + ' with ' + _key);
var x = _.filter(_lvl1, function(val, index) {
//Below condition are only true because ary are sorted and uniq.
//If both must be of same len
return val.length === lvl1[index].length
//If lenght of intersection of both values must be exactly equal
&& _.intersection(val, lvl1[index]).length === val.length;
});
//If count matches and key and _key is not in dups
// key and _key not in dups because we only want following:
// 2 with 4 -> 2
// 4 with 2 -> ignore! (we dont wanna include 4)
//Hope it makes sense
if (x.length === _lvl1.length && _.indexOf(dups, key) === -1 && _.indexOf(dups, _key) === -1) {
//Mark the key as duplicate
dups.push(key);
}
}
});
});
console.log(dups)
希望这有帮助!
答案 1 :(得分:0)
我不确定正确理解你想要什么,但我认为答案看起来就像那样(sample):
<强>使用Javascript:强>
var data = {
2: [[1,2],[3,4,5],[6,7]],
3: [[1,2],[3,4],[6,7]],
4: [[1,2],[3,4,5],[6,7]],
5: [[10,2],[3,4,5],[60,7]]
};
var find = function(input){
var res = [];
for(var prop in input){
var start = false;
for(var prop2 in input){
if(start){
var flag = JSON.stringify(input[prop]) == JSON.stringify(input[prop2]);
if(flag){
var flag3 = true;
for(var j = 0; j < res.length; j++)
if(JSON.stringify(input[prop]) == JSON.stringify(input[res[j]])){
flag3 = false
break;
}
if(flag3)
res.push(prop);
break;
}
}
else{
if(prop == prop2)
start = true;
}
}
}
return res;
}
var answer = find(data);