SNos SNos - 6 months ago 27
Javascript Question

jQuery - Search for similar elements in array

I am trying to search in an array for similar elements. For example if in my array I have the name elements like

Sarah, sara, sarah
and in the input field I type and search for
sara
the result should give me all the similar result.

Here is the fiddle however, it just looks for the correct element and it is not case insensitive.

How can approach this in order to have a case insensitive search and like the sql search
LIKE %...%
;

So far I have

$("#SearchBtn").click(function() {

var searchInput = $("#SearchInput").val();

if (searchInput == "") {

alert("Search field is empty");

} else {

for (var i = 0; i < array.length; i++) {

if ((array[i][0] == searchInput) || (array[i][1] == searchInput) || (array[i][2] == searchInput) || (array[i][3] == searchInput) || (array[i][4] == searchInput)) {

alert(array[i]);

}

}

}

});

Answer

For the case insensitive part, you can use toLowerCase both on input string and search string.

After that you can use indexOf to find if the input string is "similar" to your search pattern.

However, similarity between strings might be a bit more complicated. For example, you could consider that "sora" is similar to "sara" while "sarasara" not...

In that case, you would need Hamming distance or similar distance functions and a similarity threshold.

In addition, toLowerCase might not work with respect to globalization, and you would have to consider toLocalLowerCase.

Have a look at the simple version in this fiddle:

var array = [
  ["Andrew", "London", "Male", "waiter", "single"],
  ["John", "rome", "Male", "designer", "Married"],
  ["Sarah", "new York", "Female", "broker", "single"],
  ["Annah", "UK", "Female", "waiter", "maRRied"],
  ["sara", "Tokio", "Female", "Waiter", "single"],
  ["John", "Naples", "male", "Chef", "married"]
];

//Search Box

$("#SearchBtn").click(function() {

  var searchInput = $("#SearchInput").val().toLowerCase();

  if (searchInput == "") {

    alert("Search field is empty");

  } else {

    for (var i = 0; i < array.length; i++) {
      if ((array[i][0].toLowerCase().indexOf(searchInput) >= 0) 
      ||(array[i][1].toLowerCase().indexOf(searchInput) >= 0)
      ||(array[i][2].toLowerCase().indexOf(searchInput) >= 0)
      ||(array[i][3].toLowerCase().indexOf(searchInput) >= 0)
      ||(array[i][4].toLowerCase().indexOf(searchInput) >= 0)) {

				alert (array[i]);

      } 

    }

  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="custom-search-form" class="form form-inline navbar-form ">
  <div class="input-group">

    <input id="SearchInput" type="text" name="mapSearch" value="" placeholder="Key Search" class="form-control">
    <span class="input-group-btn">
                    <button id="SearchBtn" type="button" class="btn btn-info" style="height:25px;">Search</button>
                </span>

  </div>