javascript search function for text in array code example

Example 1: find string in array javascript

var myarr = ["I", "like", "turtles"];
var arraycontainsturtles = (myarr.indexOf("turtles") > -1);

Example 2: function search in javascript array

// function to search array using for loop
function findInArray(ar, val) {
    for (var i = 0,len = ar.length; i < len; i++) {
        if ( ar[i] === val ) { // strict equality test
            return i;
        }
    }
    return -1;
}

// example array
var ar = ['Rudi', 'Morie', 'Halo', 'Miki', 'Mittens', 'Pumpkin'];
// test the function 
alert( findInArray(ar, 'Rudi') ); // 0 (found at first element)
alert( findInArray(ar, 'Coco') ); // -1 (not found)

Example 3: search input at array javascript

var people = [
  {
    name: "John Smith",
    url: "http://example.com/johnsmith"
  },
  {
    name: "John Johnson",
    url: "http://example.com/johnjohnson"
  },
  {
    name: "Bob Thompson",
    url: "http://example.com/bobthompson"
  },
  {
    name: "Smith Sanchez",
    url: "http://example.com/smithsanchez"
  },
  {
    name: "Bob Sanchez",
    url: "http://example.com/bobsanchez"
  }
];
$("#search-input").on("keyup", function(){
  var searchFor = $("#search-input").val().toLowerCase();
  var results = [];
  for(var i=0;i<people.length;i++){
    if(people[i].name.toLowerCase().indexOf(searchFor) > -1)
      results.push("<a href='"+people[i].url+"' target='_blank'>"+people[i].name+"</a>")
  }
  if(results.length == 0)
    $("#search-results").html("No Results Found");
  else
    $("#search-results").html(results.join("<br>"));
});