JS基于两个嵌套元素数组的比较返回数组

JS Return array based on the comparison of two arrays with nested elements

本文关键字:数组 返回 比较 元素 于两个 嵌套 JS      更新时间:2023-09-26

使用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))