我正在尝试创建一个可以在两个数组中找到匹配项的过滤器

时间:2015-04-15 00:06:09

标签: angularjs

我有两个字符串数组,title和title2,我想创建第三个匹配数组。我没有运气过滤器里面的for循环,我想过使用forEach,但是,这似乎需要一个字典类型的对象。

        .filter('findMatches', function() {   
        //   this filter finds matching strings
        return function isMatch(title, title2){
        var matches = [];
        //for (i = 0; i < title.length; i++) { 
        matches.push("");

        return matches;

我不确定这是否有用,但我之前在python中写过这个,如下所示,但是,如果可以动态找到匹配项,我现在想做一个angularJS过滤器。

    Both = []
    for x in C:
        if x in D:
            Both.append(x)
    for x in range(len(Both)):
        Both[x]=str(Both[x])
    Final = []
    for x in set(Both):
        Final.append(x)
    MissingA = []
    for x in C:
        if x not in Final and x not in MissingA:
            MissingA.append(x)
    for x in range(len(MissingA)):
        MissingA[x]=str(MissingA[x])
    MissingB = []
    for x in D:
        if x not in Final and x not in MissingB:
            MissingB.append(x)
    for x in range(len(MissingB)):
        MissingB[x]=str(MissingB[x])

感谢下面两个人的帮助。我仍然无法弄清楚这一点。我在这里尝试了下面的方法二但它没有用。

http://plnkr.co/edit/SEi3DU0PoOSPx9AZBrzP?p=preview

2 个答案:

答案 0 :(得分:0)

我不确定自定义过滤器是否适合此问题。我可能会创建一个服务,将其作为单个数组返回,我可以执行匹配(或只是让服务执行匹配)。

更简单的解决方案如下所示:

    <input type="text" ng-model="query" />

  <ul>
    <li ng-repeat="title in title1 | filter: query">{{title}}</li>
    <li ng-repeat="title in title2 | filter: query">{{title}}</li>
  </ul>

答案 1 :(得分:0)

你可以简单地将其作为

    .filter('findMatches', function() {   
         return function isMatch(title, title2){
            var matches = [];
            for (i = 0; i < title.length; i++) { 
              if(title2.indexOf(title[i]) > -1){
                matches.push(title[i]);
              }
            }
             return matches;
         }
})