3

What is the most efficient way to filter a list of strings character by character?

var term = "Mike";
angular.forEach($scope.contacts, function(contact, key) {

    // if I had the whole term and 
    // contact.name == Mike then this is true
    contact.name == term;

});

The above would be fine, but if I am building a search how can I filter character by character?

var term = "Mi";
angular.forEach($scope.contacts, function(contact, key) {

    // contact.name == Mike, but term == Mi how can I get this to return true?
    contact.name == term;

});
1
  • You really have to define what a partial match would mean, so for your last example there, would "Tommie" be a valid match? Depending on the rules you come up with there are lots of different ways to do this. Commented Jan 14, 2016 at 15:33

1 Answer 1

5

Use indexOf

var term = "Mi";
angular.forEach($scope.contacts, function(contact, key) {

    // contact.name == Mike, but term == Mi how can I get this to return true?
    contact.name.indexOf(term) > -1;

});

If you want case insensitive testing, you can do

    var term = "Mi";
    var regex = new RegExp(term, 'i');

    angular.forEach($scope.contacts, function(contact, key) {

        // contact.name == Mike, but term == Mi how can I get this to return true?
        regex.test(contact.name);

    });
Sign up to request clarification or add additional context in comments.

5 Comments

Your case-insensitive solution uses a regular expression, this can change the meaning of term for characters with special meaning in the regular expression language. Instead consider converting both values to the same case (ie. toLowerCase()) and do an indexOf.
Great advice Halcyon, definitely will do that now :)
@Halcyon, I am not sure what you mean by this can change the meaning of term. Do you mean linguistically, or will there be unintended side effects programmatically?
If term is Mi* you will match mi, miii but also m.
@Halcyon, sorry, still not understanding :-). Doing this in the console new RegExp('Mi', 'i').test('m') gives me false

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.