Revision:
The filter() method creates a new array filled with elements that pass a test provided by a function. The filter() method does not execute the function for empty elements and does not change the original array.
The filter() method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
Syntax: array.filter(function(currentValue, index, arr), thisValue)
parameters:
function() : required; a function to run for each array element; the function is a predicate, to test each element of the array; it returns a value that coerces to true to keep the element, or to false otherwise; the function is called with the following arguments: element, index, array;
currentValue: required; the value of the current element;
index: optional; the index of the current element;
arr: optional; the array of the current element;
thisValue: optional; default "undefined"; a value passed to the function as its value.
return value: an array, containing the elements that pass the test. If no elements pass the test it returns an empty array.
Syntax examples:
// Arrow function filter((element) => { /* … */ } ) filter((element, index) => { /* … */ } ) filter((element, index, array) => { /* … */ } ) // Callback function filter(callbackFn) filter(callbackFn, thisArg) // Inline callback function filter(function(element) { /* … */ }) filter(function(element, index) { /* … */ }) filter(function(element, index, array){ /* … */ }) filter(function(element, index, array) { /* … */ }, thisArg)
Examples
<div class="spec"> <p id="filter_demo"></p> <p id="filter_demo1"></p> </div> <script> const ages = [12, 18, 32, 33, 16, 40, 10]; document.getElementById("filter_demo").innerHTML = "original array: ages = " + ages; document.getElementById("filter_demo1").innerHTML = "18 or more: " + ages.filter(checkAdult); function checkAdult(age) { return age >= 18; } </script>
Examples
<div class="spec"> <p id="filter_demo2"></p> <p><input type="number" id="ageToCheck" value="30"></p> <button onclick="filterAges()">test</button> <p id="filter_demo3"></p> </div> <script> const ages1 = [10, 18, 32, 33, 12, 40, 17, 45]; document.getElementById("filter_demo2").innerHTML = "original array: ages = " + ages1; function checkAge(age) { return age > document.getElementById("ageToCheck").value; } function filterAges() { document.getElementById("filter_demo3").innerHTML = ages1.filter(checkAge); } </script>
Examples
<div class="spec"> <p id="filter_demo4"></p> <p id="filter_demo5"></p> </div> <script> const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present', 'today', 'overturn']; document.getElementById("filter_demo4").innerHTML = "original array: " + words; const result = words.filter(word => word.length > 6); document.getElementById("filter_demo5").innerHTML = "words longer than six letters: " + result; </script>
Examples
<div class="spec"> <p id="filter_demo6"></p> <p id="filter_demo7"></p> </div> <script> let cities = [ {name: 'Los Angeles', population: 3792621}, {name: 'New York', population: 8175133}, {name: 'Chicago', population: 2695598}, {name: 'Houston', population: 2099451}, {name: 'Philadelphia', population: 1526006} ]; document.getElementById("filter_demo6").innerHTML = "list of cities: " + "<br>" + cities.map(e =>e.name + " -- " + e.population).join(' ,<br> ') ; let bigCities = cities.filter(function (e) { return e.population > 3000000; }); document.getElementById("filter_demo7").innerHTML = "population above 3 million: " + '<br>' + bigCities.map(e => e.name + " -- " + e.population).join(' ,<br> ');
Examples
<div class="spec"> <p id="filter_demo8"></p> <p id="filter_demo9"></p> </div> <script> var participants = [ { name: 'Anna', age: 19 }, { name: 'Josh', age: 17 }, { name: 'Mary', age: 15 }, { name: 'Emily', age: 14 }, { name: 'Caroline', age: 24 }, { name: 'Sam', age: 16 }]; document.getElementById("filter_demo8").innerHTML = "all participants and their age: " +'<br>' + participants.map(e => e.name + " -> " + e.age).join(',<br>'); function filterByAge() { var result = participants.filter(participant => participant.age > 18); document.getElementById("filter_demo9").innerHTML = "people older than 18:" + '<br>' + result.map(e => e.name + " -> " + e.age).join(',<br>'); } filterByAge();
<div class="spec"> <input type="text" id="filter1" onkeyup="filterList()" placeholder="Search for names.. " title="Type in a name"> <ul id="myUL"> <li><a href="#">Adele</a></li> <li><a href="#">Agnes</a></li> <li><a href="#">Billy</a></li> <li><a href="#">Bob</a></li> <li><a href="#">Calvin</a></li> <li><a href="#">Christina</a></li> <li><a href="#">Cindy</a></li> </ul> </div> <style> #filter1 {background-image: url('search.png'); background-position: 1vw 1.2vw; background-repeat: no-repeat; width: 80%; font-size: 1.16vw; padding: 1.2vw 2vw 1.2vw 4vw; border: 0.2vw solid blue; margin-bottom: 1.2vw;} #myUL {list-style-type: none; padding: 0; margin: 0;} #myUL li a {border: 0.2vw solid green; margin-top: -1px; /* Prevent double borders */ background-color: #f6f6f6; padding: 1.2vw; text-decoration: none; font-size: 1.16vw; color: black; display: block; } #myUL li a:hover:not(.header) { background-color: #eee;} </style> <script> function filterList() { var input, filter, ul, li, a, i, txtValue; input = document.getElementById("filter1"); filter = input.value.toUpperCase(); ul = document.getElementById("myUL"); li = ul.getElementsByTagName("li"); for (i = 0; i < li.length; i++) { a = li[i].getElementsByTagName("a")[0]; txtValue = a.textContent || a.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { li[i].style.display = ""; } else { li[i].style.display = "none"; } } } </script>
Remove toUpperCase() if you want to perform a case-sensitive search.
Name | Country |
---|---|
Wilfried Vanmoer | Belgium |
Leonel Messi | Chili |
Franz Beckenbauer | Germany |
Johan Cruyff | Netherlands |
<div class="spec"> <input type="text" id="filter2" onkeyup="filterTable()" placeholder="Search for names.."> <table id="myTable"> <tr class="header"> <th style="width:60%;">Name</th> <th style="width:40%;">Country</th> </tr> <tr> <td>Wilfried Vanmoer</td> <td>Belgium</td> </tr> <tr> <td>Leonel Messi</td> <td>Chili</td> </tr> <tr> <td>Franz Beckenbauer</td> <td>Germany</td> </tr> <tr> <td>Johan Cruyff</td> <td>Netherlands</td> </tr> </table> </div> <style> #filter2{background-image: url('search.png'); background-position: 1vw 1.2vw; background-repeat: no-repeat; width: 80%; font-size: 1.16vw; padding: 1.2vw 2vw 1.2vw 4vw; border: 0.2vw solid skyblue; margin-bottom: 1.2vw;} #myTable {border-collapse: collapse; width: 90%; border: 0.2vw solid lightgreen; font-size: 1.16vw;} #myTable th, #myTable td {text-align: left; padding: 1.2vw;} #myTable tr {border-bottom: 0.1vw solid #ddd;} #myTable tr.header, #myTable tr:hover {background-color: aliceblue;} </style> <script> function filterTable() { var input, filter, table, tr, td, i, txtValue; input = document.getElementById("filter2"); filter = input.value.toUpperCase(); table = document.getElementById("myTable"); tr = table.getElementsByTagName("tr"); // Loop through all table rows, and hide those who don't match the search query for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[0]; if (td) { txtValue = td.textContent || td.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } } </script>
Change tr[i].getElementsByTagName('td')[0] to [1] if you want to search for "Country" (index 1) instead of "Name" (index 0).
<div> <!-- Control buttons --> <div id="filterButtons"> <button class="btn active" onclick="filterSelection('all')"> Show all</button> <button class="btn" onclick="filterSelection('cars')"> Cars</button> <button class="btn" onclick="filterSelection('animals')"> Animals</button> <button class="btn" onclick="filterSelection('fruits')"> Fruits</button> <button class="btn" onclick="filterSelection('colors')"> Colors</button> </div> <!-- The filterable elements. --> <div class="container"> <div class="filterDiv cars">BMW</div> <div class="filterDiv colors fruits">Orange</div> <div class="filterDiv cars">Volvo</div> <div class="filterDiv colors">Red</div> <div class="filterDiv cars animals">Mustang</div> <div class="filterDiv colors">Blue</div> <div class="filterDiv animals">Cat</div> <div class="filterDiv animals">Dog</div> <div class="filterDiv fruits">Melon</div> <div class="filterDiv fruits animals">Kiwi</div> <div class="filterDiv fruits">Banana</div> <div class="filterDiv fruits">Lemon</div> <div class="filterDiv animals">Cow</div> </div> </div> <style> .container {overflow: hidden;} .filterDiv {float: left; background-color: dodgerblue; color: skyblue; width: 10vw; line-height: 10vw; text-align: center; margin: 0.2vw; display: none;} /* The "show" class is added to the filtered elements */ .show {display: block;} .btn {border: none; outline: none; padding: 1.2vw 1.6vw; color: red; background-color: darkolivegreen; cursor: pointer;} .btn:hover { background-color: skyblue; color:green;} .btn.active {background-color: #666;color: white;} </style> <script> filterSelection("all") function filterSelection(c) { var x, i; x = document.getElementsByClassName("filterDiv"); if (c == "all") c = ""; // Add the "show" class (display:block) to the filtered elements, and remove the "show" class from the elements that are not selected for (i = 0; i < x.length; i++) { w3RemoveClass(x[i], "show"); if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show"); } } // Show filtered elements function w3AddClass(element, name) { var i, arr1, arr2; arr1 = element.className.split(" "); arr2 = name.split(" "); for (i = 0; i < arr2.length; i++) { if (arr1.indexOf(arr2[i]) == -1) { element.className += " " + arr2[i]; } } } // Hide elements that are not selected function w3RemoveClass(element, name) { var i, arr1, arr2; arr1 = element.className.split(" "); arr2 = name.split(" "); for (i = 0; i < arr2.length; i++) { while (arr1.indexOf(arr2[i]) > -1) { arr1.splice(arr1.indexOf(arr2[i]), 1); } } element.className = arr1.join(" "); } // Add active class to the current control button (highlight it) var btnContainer = document.getElementById("filterButtons"); var btns = btnContainer.getElementsByClassName("btn"); for (var i = 0; i < btns.length; i++) { btns[i].addEventListener("click", function() { var current = document.getElementsByClassName("active"); current[0].className = current[0].className.replace(" active", ""); this.className += " active"; }); } </script>
<div class="spec"> <div class="dropdown"> <button onclick="filterDropdown()" class="dropbtn">Dropdown</button> <div id="filter4" class="dropdown-content"> <input type="text" placeholder="Search.." id="myInput" onkeyup="filterDropdown2()"> <a href="#about">About</a> <a href="#base">Base</a> <a href="#blog">Blog</a> <a href="#contact">Contact</a> <a href="#custom">Custom</a> <a href="#support">Support</a> <a href="#tools">Tools</a> </div> </div> </div> <style> .dropbtn {background-color: #04AA6D; color: white; padding: 1.6vw; font-size: 1.2vw; border: none; cursor: pointer;} .dropbtn:hover, .dropbtn:focus {background-color: dodgerblue;} #myInput {box-sizing: border-box; background-image: url('search.png'); background-position: 1.4vw 1.2vw; background-repeat: no-repeat; font-size: 1.2vw; padding: 1.4vw 2vw 1.2vw 4.5vw; border: none; border-bottom: 1px solid #ddd;} #myInput:focus {outline: 0.3vw solid #ddd;} .dropdown {position: relative; display: inline-block;} .dropdown-content {display: none; position: absolute; background-color: antiquewhite; min-width: 23vw; border: 0.2vw solid skyblue; z-index: 1;} .dropdown-content a {color: black; padding: 1.2vw 1.6vw; text-decoration: none; display: block;} .dropdown-content a:hover {background-color: #f1f1f1} /* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */ .show {display:block;} </style> <script> /* When the user clicks on the button, toggle between hiding and showing the dropdown content */ function filterDropdown() { document.getElementById("filter4").classList.toggle("show"); } function filterDropdown2() { var input, filter, ul, li, a, i; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); div = document.getElementById("filter4"); a = div.getElementsByTagName("a"); for (i = 0; i < a.length; i++) { txtValue = a[i].textContent || a[i].innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { a[i].style.display = ""; } else { a[i].style.display = "none"; } } } </script>