简体   繁体   English

数组对象差异javascript angularjs

[英]Array objects difference javascript angularjs

I have 2 array objects and I want to get the difference between them as follows: 我有2个数组对象,我想得到它们之间的区别如下:

array1 = [{"name":"MPCC","id":"tool:mpcc"}, {"name":"APP","id":"tool:app"}, {"name":"AII","id":"tool:aii"}, {"name":"VZZ","id":"tool:vzz"}, {"name":"USU","id":"tool:usu"}]

array2 = [{"name":"APP","id":"tool:app"}, {"name":"USU","id":"tool:usu"}]

result = [{"name":"MPCC","id":"tool:mpcc"}, {"name":"AII","id":"tool:aii"}, {"name":"VZZ","id":"tool:vzz"}]

Here is the code: 这是代码:

$scope.initial = function(base, userData){
    var result = [];
    angular.forEach( base, function(baseItem) {
        angular.forEach( userData, function( userItem ) {
            if ( baseItem.id !== userItem.id ) {
                if (result.indexOf(baseItem) < 0) { 
                    result.push(baseItem);
                }
            }
        });
    });
    return result;
}
$scope.initial(array1, array2);

The problem with the above code is I dont get the desired result. 上面代码的问题是我得不到想要的结果。 Please let me know what is going wrong. 请告诉我出了什么问题。

That is not related to Angular. 这与Angular无关。

You could do something like this: 你可以这样做:

var result = array1.filter(function(item1) {
  for (var i in array2) {
    if (item1.id === array2[i].id) { return false; }
  };
  return true;
});

Or with ES6 syntax: 或者使用ES6语法:

var result = array1.filter(i1 => !array2.some(i2 => i1.id === i2.id));

I think this is not related to Angular itself. 我认为这与Angular本身无关。 You're looking for an algorithm to compute a difference between 2 sets. 您正在寻找一种算法来计算2组之间的差异。

The topic has already been discussed . 这个话题已经讨论 You may also be interested on this underscore plugin 您可能也对此下划线插件感兴趣

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM