I am doing the #JavaScript30 challenge and challenge 06 is to write a "type ahead" application for searching for cities/states. The basic challenge of filtering based on a simple string was rather trivial, so I wanted to add AND and OR functionality using + and ,.

I came up with a recursive solution, but when handling the ANDs I have a feeling that the way I accomplished it is inefficient and has a higher-than-necessary Big O complexity. Below is the code in question, and I will also post a link to a working demo to play around with.

If anyone can show me a more efficient way to do this, or let me know if this is as efficient as it can get, it would be greatly appreciated!

Working DEMO

Function in question

function handleAnds (andArray, citiesArr) {
  // grab last AND condition to work from left to right, recursively
  var lastAnd = andArray.pop().trim();
  var matches = [];
  if (~lastAnd.indexOf(",")){
    // handle OR conditions
    matches = handleOrs(lastAnd.split(","), citiesArr);
  else {
    matches = citiesArr.filter(function (city) {
      return (
        (checkObjectPropertyValue(city, "city", lastAnd) ||
         checkObjectPropertyValue(city, "state", lastAnd))

  if (andArray.length) {
    /* Code In Question */
    var extras = handleAnds(andArray, citiesArr);
    matches = matches.filter(function (elem) {
      return ~extras.indexOf(elem);
    /* /Code In Question */
    return matches; 
  else {
    return matches;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.