- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the role of filter() method in JavaScript?
JavaScript array filter() method creates a new array with all elements that pass the test implemented by the provided function.
The following are the parameters −
callback − Function to test each element of the array.
thisObject − Object to use as this when executing callback.
You can try to run the following code to learn how to work with filter() method in JavaScript −
Example
<html> <head> <title>JavaScript Array filter Method</title> </head> <body> <script> if (!Array.prototype.filter) { Array.prototype.filter = function(fun /*, thisp*/) { var len = this.length; if (typeof fun != "function") throw new TypeError(); var res = new Array(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) { var val = this[i]; // in case fun mutates this if (fun.call(thisp, val, i, this)) res.push(val); } } return res; }; } function isBigEnough(element, index, array) { return (element >= 10); } var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); document.write("Filtered Value : " + filtered ); </script> </body> </html>
Advertisements