我有几个具有相同ID的数组。我想要实现的是在普通的javascript中获取数组之间的交集,没有库。如果Ids和arraypicklist的匹配值在2个或更多数组之间不相等,我应该得到一个具有匹配ID的数组。
以下是我尝试的示例,但最终没有任何ID,我希望至少有1个匹配。在这种情况下,Id:123与第一和第二阵列中的匹配一样。所以我希望
intersection = [{"Id":"123","arrayPicklist":"Categorie__c"},{"Id":"123","arrayPicklist":"Regio__c"}];
小提琴:https://jsfiddle.net/ozckc0tw/4/
var buckets = [[{"Id":"123","arrayPicklist":"Categorie__c"}],
[{"Id":"123","arrayPicklist":"Regio__c"}],
[{"Id":"124","arrayPicklist":"Categorie__c"}],
[{"Id":"123","arrayPicklist":"Regio__c"},{"Id":"125","arrayPicklist":"Regio__c"},{"Id":"123","arrayPicklist":
"Regio__c"},{"Id":"126","arrayPicklist":"Regio__c"}]]
function IntersectionByKey(key) {
var i,
j,
k,
ret = [],
item,
args = [].slice.call(arguments, 1);
args.sort(function(a, b) {return a.length - b.length});
i:for(i=0; i<args[0].length; i++) {
item = [Object.assign(args[0][i], {})];
j:for(j=1; j<args.length; j++) {
for(k=0; k<args[j].length; k++) {
if(key in args[0][i] && args[0][i][key] == args[j][k][key]){
item.push(Object.assign(args[j][k], {}));
continue j;
}
}
continue i;
}
ret.push(item);
}
return ret;
}
var key = 'Id';
var intersection = IntersectionByKey.apply(null, [key].concat(buckets));
console.log('intersection '+JSON.stringify(intersection))
答案 0 :(得分:0)
完成,抱歉,但我没有查看你的代码,我根据你的要求尝试了我的逻辑,你可以使用它。 my logic
var buckets = [
[{
"Id": "123",
"arrayPicklist": "Categorie__c"
}],
[{
"Id": "123",
"arrayPicklist": "Regio__c"
}],
[{
"Id": "124",
"arrayPicklist": "Categorie__c"
}],
[{
"Id": "123",
"arrayPicklist": "Regio__c"
}, {
"Id": "125",
"arrayPicklist": "Regio__c"
}, {
"Id": "123",
"arrayPicklist": "Regio__c"
}, {
"Id": "126",
"arrayPicklist": "Regio__c"
}]
],
intersection = [{
"Id": "123",
"arrayPicklist": "Categorie__c"
}, {
"Id": "123",
"arrayPicklist": "Regio__c"
}];
var resArray = [];
for (var j = 0; j < intersection.length; j++) {
for (var i = 0; i < buckets.length; i++) {
for (var k = 0; k < buckets[i].length; k++) {
if (buckets[i][k].Id == intersection[j].Id && buckets[i][k].arrayPicklist == intersection[j].arrayPicklist) {
resArray.push(buckets[i][k]);
}
}
}
}
console.log(resArray);