Q:

Custom search filter for AngularJs

Let suppose I have an array of strings like ["don't worry", "worry", "Always be happy and don't worry" ]
When I search for worry,using default search filter on ng-repeat, it gives me all three results irrespective of the position at which worry is in the string to be searched.
I am trying to make a custom search filter for ng-repeat such that on searching worry I should get results sorted according to the position of "worry" in the original string.
So upon searching for word "worry" in the above array, my expected output will be 
["worry", "don't worry", "Always be happy and don't worry"]. 
Is this possible?  

A:

Could you try this? 
app.filter('wordsFilter', function() {
   return function(items, word) {
    var filtered = [];

    angular.forEach(items, function(item) {
        if(item.indexOf(word) !== -1){
            filtered.push(item);
        }
    });

    filtered.sort(function(a,b){
        if(a.indexOf(word) < b.indexOf(word)) return -1;
        else if(a.indexOf(word) > b.indexOf(word)) return 1;
        else return 0;
    });

    return filtered;
  };
});

I hope it helps!

