JavaScript - Array filter() Method


Advertisements


Description

Javascript array filter() method creates a new array with all elements that pass the test implemented by the provided function.

Syntax

Its syntax is as follows −

array.filter(callback[, thisObject]);

Parameter Details

  • callback − Function to test each element of the array.

  • thisObject − Object to use as this when executing callback.

Return Value

Returns created array.

Compatibility

This method is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. To make it work, you need to add the following code at the top of your 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;
   };
}

Example

Try the following example.

<html>
   <head>
      <title>JavaScript Array filter Method</title>
   </head>
   
   <body>
   
      <script type="text/javascript">
         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>

Output

Filtered Value : 12,130,44 

javascript_arrays_object.htm

Advertisements