Search and Filter Array in JavaScript
 
Author:
Filed Under: JavaScript  |  Snippets
Published Date: Feb 23, 2011
Views: 1610
 

Abstract: Here Mudassar Ahmed Khan has described how to filter or search for substring in array in JavaScript

Comments:  1

 

This is a short code snippet article where I am describing how to filter array client side in JavaScript.
JavaScript Snippet
Below is the snippet that filters the JavaScript array of strings based on the text typed in the textbox. The filtered results are displayed in HTML span dynamically as you type.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
    var arr = ["Ana Trujillo",
        "Antonio Moreno",
        "Thomas Hardy",
        "Christina Berglund",
        "Hanna Moos",
        "Frédérique Citeaux",
        "Martín Sommer",
        "Laurence Lebihan",
        "Victoria Ashworth",
        "Janine Labrune"];
 
    function Filter(value) {
 
        var filterArr = [];
        for (var i in arr) {
            if (arr[i].toLowerCase().indexOf(value.toLowerCase()) != -1) {
                filterArr[filterArr.length] = arr[i];
            }
        }
        var result = "";
        for (var i in filterArr) {
            result += filterArr[i] + "<br />";
        }
        if (result != "") {
            document.getElementById("lblResult").innerHTML = result;
        } else {
            document.getElementById("lblResult").innerHTML = "No matches!";
        }
    }
    window.onload = function () {
        Filter("");
    };
</script>
</head>
<body>
<input type = "text" onkeyup = "Filter(this.value)" id = "txtFilter" /><br />
<span id="lblResult"></span>
</body>
</html>
 
Demo
You can view the above script in action below.

 

The above code has been tested in the following browsers

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.


Downloads
You can download the sample source code using the download link provided below.
FilterArrayInJavaScript.zip
 








Related Articles



Comments



Add comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
Please do not post code, scripts or snippets.

Name*: Required
Email*: Required
Comment*: Required
Security code*: CaptchaInvalid Security Code
  Submit