比较两个数组和concat没有重复

时间:2017-02-14 09:25:36

标签: angularjs arrays

我有两个数组。我可以通过点击searchWords中的单词进行推送和拼接,该单词会向currentWordlist添加或删除单词。

我想要的是一个按钮,它将所有searchWords转移到currentWordlist,而不会覆盖当前在currentWordlist上的单词。

我想出了这段代码:

$scope.addAll = function () {
    var searchWords = [];
    var currentWords = [];

    // safes all searchwords to the array
    for (var i = 0; i < $scope.searchWords.length; i++) {
      searchWords.push($scope.searchWords[i]);
    }

    // safes all currentwords to the array
    for (var j = 0; j < $scope.currentWordlist.length; j++) {
      currentWords.push($scope.currentWordlist[j]);
    }

    console.log("searchWords " + searchWords.length);
    console.log("currentWords " + currentWords.length);

    angular.forEach(searchWords, function(value1, key1) {
      angular.forEach(currentWords, function(value2, key2) {
        if (value1._id !== value2._id) {
          $scope.currentWordlist.push(value1);
        }
      });
    });
  };

我浏览了两个数组并保护它们,以便我可以使用我的两个angular.forEach中的数组来检查是否存在重复数据。如果我不推送到currentWordlist。但它不起作用。我收到[ngRepeat:dupes]错误,但我不能使用$ index跟踪,因为否则从列表中删除会删除错误的单词。我觉得我在做一些严重错误的事情,但到目前为止我找不到(试验和错误的时间:0)

2 个答案:

答案 0 :(得分:3)

我建议使用带有unique指令的角度ng-repeat过滤器。代码如下:

$scope.addAll = function () {
  // use angular.copy to create a new instance of searchWords
  $scope.combinedWords = angular.copy($scope.searchWords).concat($scope.currentWordlist);
};

然后在你看来:

<div ng-repeat="word in combinedWords | unique:'_id'">
  {{word}}
</div>

用法:

colection | uniq: 'property'

也可以通过嵌套属性进行过滤:

colection | uniq: 'property.nested_property'

答案 1 :(得分:2)

你可以这样做

    angular.forEach($scope.searchWords, function(value1, key1) {
      var temp=true;
      angular.forEach($scope.currentWordlist, function(value2, key2) {
        if (value1.id === value2.id)
          temp=false;
      });
      if(temp)
        $scope.currentWordlist.push(value1);
    });

var app = angular.module("app", []);
app.controller("ctrl", function($scope) {
  
  $scope.searchWords=[{id:1,name:'A'},{id:2,name:'B'},{id:1,name:'A'},{id:4,name:'D'}];
  $scope.currentWordlist=[];
  $scope.addAll = function() {
    
    angular.forEach($scope.searchWords, function(value1, key1) {
      var temp=true;
      angular.forEach($scope.currentWordlist, function(value2, key2) {
        if (value1.id === value2.id)
          temp=false;
      });
      if(temp)
        $scope.currentWordlist.push(value1);
    });
    
    console.log($scope.currentWordlist);
  };

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <button ng-click="addAll(newWord)">Add</button>
  <div>{{currentWordlist}}</div>
</div>