Search code examples
javascriptlodashmd-autocomplete

Filtering an array of objects on 1 property not limited to start of text


I'm trying to combine lodash with ngMaterial and md-autocomplete.

I have a collection of user objects in an array:

var User.collection = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 34 },
  { 'user': 'fred',   'age': 42 },
  { 'user': 'barney', 'age': 36 }
];

I am trying to filter this list to return only the ones matching the search query for example

var query = "fr"

I get the filter working with this controller function:

collectionFilter: function(query) {
    var lowercaseQuery = angular.lowercase(query);
    return _.filter(User.collection, function(obj) {
        return (angular.lowercase(obj.name).indexOf(lowercaseQuery) === 0)
    })
}

Issue with this is that I won't get any results if I star typing the middle of the name like "rne".


Solution

  • You're checking for === 0. Try > -1.

    Indexof returns the index (position) of the parameter within the string. The first position is 0. This is why it only shows results that match from the first character.

    If you like, try changing it to === 1 and search for "re".