How to filter Array in Javascript?
We can filter Array in Javascript by using filter() method. filter() method returns all the elements inside of an array object which matched the provided condition for filtering it. This method does not changes the source array but returns a filtered array.
Example of filter() method:
var names = ["Mark","Mathew","Monica","Hayden","Rick","Sam","Rose","Maxwell","Alex","Johnny","John","David","Adam","Ricky","Jay"] document.getElementById("filteredNames").innerHTML = names.filter(name => name.length === 4);
This will return all the names whose length is 4.
Output:
Mark,Rick,Rose,Alex,John,Adam
Another example:
We will filter another array on the basis of its category. Here we have a simple Javascript array:
var items = [{"name":"Apple", "category":"fruit"},{"name":"Mango", "category":"fruit"}, {"name":"Carrot", "category":"vegetable"},{"name":"Brocolli", "category":"vegetable"}]
We will filtered out categories and return the filtered items.
var filteredItems = items.filter(item => item.category === categoryName);
Example:
<html> <head> <title>Javascript Array filter()</title> <Style> body { background-color:#fafafa; padding:20px; font-family:Arial; } </Style> </head> <body> Category name: <input type="text" id="txtCategoryName"/> <button onclick="filterNames()">Filter Names</button> <p id="filteredNames"></p> <script> var items = [{"name":"Apple", "category":"fruit"},{"name":"Mango", "category":"fruit"}, {"name":"Carrot", "category":"vegetable"},{"name":"Brocolli", "category":"vegetable"},] function filterNames() { var categoryName = document.getElementById("txtCategoryName"); var filteredItems = items.filter(item => item.category === categoryName.value); console.log(filteredItems); document.getElementById("filteredNames").innerHTML = JSON.stringify(filteredItems); } </script> </body> </html>
Output: