Filtering a name Array in JavaScript I was wondering if there is a better, more elegant way to write the following JavaScript code block:

var searchString = 'ma';
var names = ['Mark Kennel', 'Hellen Smith', 'Jane Mary Annet', 'Peter'];

var filteredNames = names.filter(name =&gt; {
  var words = name.toLowerCase().split(' ');
  for(var i = 0; i &lt; words.length; i++) {
    if (words[i].indexOf(searchString.toLowerCase()) === 0 )
      return true;
  }
}


This runs in a function that filters an autocomplete input results. The filtering rule is:


  Show the names that have a word which begins with the searchString


The above code (with searchString = 'ma') should return an array with two names: 'Mark Kennel' and 'Jane Mary Annet'.
Well, better and more elegant are quite opinion based and depend on different things: a code can be better regarding performance but worse regarding clarity.

That being said, I'd like to drop my two cents: since you just want to know if a given word begins with the input string (which is different from containing the input string) you can use lastIndexOf, setting fromIndex as 0. That way, you don't search the whole string, but just its beginning:



var searchString = 'ma';
var names = ['Mark Kennel', 'Hellen Smith', 'Jane Mary Annet', 'Peter'];

function filterNames(arr, str) {
  return arr.filter(function(thisName) {
    return thisName.toLowerCase().split(" ").some(function(d) {
      return d.lastIndexOf(str.toLowerCase(), 0) === 0
    })
  })
}

console.log(filterNames(names, searchString))




Another obvious option here is using startsWith. However, unlike lastIndexOf, startsWith don't wok on IE (if you care for that).