In this article I will explain with an example, how to search and filter array in
JavaScript.
HTML Markup
The following HTML Markup consists of:
TextBox – For user input.
The TextBox has been assigned with an onkeyup event handler.
SPAN – For displaying the filtered records.
<input type="text" onkeyup="Filter(this.value)" id="txtFilter" />
<br />
<span id="lblResult"></span>
Searching and Filtering Array in JavaScript
Inside the
window.onload and TextBox
onkeyup event handler,
Filter JavaScript function is called.
Filter JavaScript function
Inside the
Filter JavaScript function, first an Array of names is defined and a FOR loop is executed over it.
Then, inside the FOR loop, a check is performed whether the Array index is not equal to -1 then Array is copied into another Array named filterArr.
Finally, a check is performed if the Array length is greater than zero then filtered result is displayed in the HTML SPAN element.
<script type="text/javascript">
window.onload = function () {
Filter("");
};
function Filter(value) {
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"
];
var filterArr = [];
for (var i in arr) {
if (arr[i].toLowerCase().indexOf(value.toLowerCase()) != -1) {
filterArr[filterArr.length] = arr[i];
}
}
if (filterArr.length > 0) {
document.getElementById("lblResult").innerHTML = filterArr.join("<br />");
} else {
document.getElementById("lblResult").innerHTML = "No matches!";
}
}
</script>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Downloads