JS基于两个嵌套元素数组的比较返回数组
JS Return array based on the comparison of two arrays with nested elements
使用Angular并尝试根据两个数组的比较返回结果。这是我所拥有的:
$scope.fbFriends = [{"id":1234,"name":'bob'},
{"id":4567,"name":'john'},
{"id":8910,"name":'totoro'}];
$scope.appFriends = [{"id":1,"name":'bob',"fb_id":1234},
{"id":2,"name":'john',"fb_id":4567}];
我想过滤两者中都存在的好友,只返回appFriends中不存在的fbFriends好友。这就是我所做的,但它不起作用——它的回报太多次了。
$scope.not_friends = [];
$scope.filtered = [];
for (var i=0; i < $scope.fbFriends.length; i++) {
for (var j=0; j < $scope.appFriends.length; j++) {
if ($scope.fbFriends[i].id !== $scope.appFriends[j].fb_id) {
$scope.not_friends = $scope.fbFriends[i];
$scope.filtered.push($scope.not_friends);
}
}
};
console.log($scope.filtered);
这种方法有什么错?额外的好处是,我可以把它集成到一个过滤器中,并在fbFriends的ng重复中使用吗?
谢谢!!
问题是if block
:你必须检查是否相等,然后-因为你在搜索fbFriends中不包含的朋友-删除对象。
我已经重写了你的代码,它似乎工作正常。
$scope.fbFriends = [{"id":1234,"name":'bob'},
{"id":4567,"name":'john'},
{"id":8910,"name":'totoro'}];
$scope.appFriends = [{"id":1,"name":'bob',"fb_id":1234},
{"id":2,"name":'john',"fb_id":4567}];
for (var i=0; i < $scope.appFriends.length; i++) {
// we parse the 'reference array'
for (var j=0; j < $scope.fbFriends.length; j++) {
// we check every value inside the 'container array'
if ($scope.fbFriends[j].id == $scope.appFriends[i].fb_id) {
// the element is alredy inside the appFriends
$scope.fbFriends.splice(j,1);
}
}
}
console.log($scope.fbFriends);
如需进一步参考,请参阅算法书(我的建议是Thomas H.Cormen的《算法导论》,但任何人都会这么做。)
这里有一个通用的集差运算
difference = function(a, b, eq) {
return a.filter(function(x) {
return b.every(function(y) {
return !eq(x, y)
});
});
}
其中CCD_ 2是数组,CCD_。
这就是如何将其应用于您的问题:
fbFriends = [{"id":1234,"name":'bob'},
{"id":4567,"name":'john'},
{"id":8910,"name":'totoro'}];
appFriends = [{"id":1,"name":'bob',"fb_id":1234},
{"id":2,"name":'john',"fb_id":4567}];
difference = function(a, b, eq) {
return a.filter(function(x) {
return b.every(function(y) {
return !eq(x, y)
});
});
}
onlyFb = difference(fbFriends, appFriends, function(f, a) {
return f.id === a.fb_id
});
document.write(JSON.stringify(onlyFb))
相关文章:
- 对象数组返回自最近日期以来的最高总体值
- 从多维数组返回嵌套数组
- 为什么当我点击<a>使用纯javascript;这个“;返回url,数组返回“url”;未定义”;
- 带多维数组返回字符串的json_encode;阵列”;而不是数据
- 如何将 AJAX 响应作为 JavaScript 数组返回
- 我正在尝试在 JS 中制作这个随机名称生成器.数组返回未定义
- .push() 多个对象进入 JavaScript 数组返回 'undefined'
- 如何按属性从可观察数组返回项
- 通过jquery发送的关联php数组返回[对象对象]
- 从 Javascript 中的对象数组返回单个属性的数组
- 循环遍历对象数组返回“未定义”
- 拼接数组返回空的序列
- Javascript 多维数组返回第一个值,然后失败
- Json 数组返回空值
- 从下划线.js中的数组返回一系列值
- for 语句不从数组返回值
- MongoDB从数组返回特定字段
- 试图将数组返回到表中的列表中
- Javascript中的二维数组返回未定义的数组
- 将函数数组作为布尔值数组返回