Open In App

Array filter() Method – TypeScript

Last Updated : 10 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The Array.filter() is an inbuilt TypeScript function which is used to creates a new array with all elements that pass the test implemented by the provided function. 
Syntax:

array.filter(callback[, thisObject])

Parameter: This methods accepts two parameter as mentioned and described below:

  • callback : This parameter is the Function to test for each element.
  • thisObject : This parameter is the Object to use as this when executing callback.

Return Value: This method returns created array. 
Below examples illustrate the Array filter() method in TypeScript
Example 1: 

JavaScript
<script>
    // check for positive number 
    function ispositive(element, index, array)
    { 
       return element > 0;
    } 
      
    // Driver code
    var arr = [ 11, 89, -23, 7, 98 ]; 
    
    // check for positive number 
    var value = arr.filter(ispositive); 
    console.log( value );
</script>

Output: 

[11,89,7,98]

Example 2: 

JavaScript
    // check for odd number 
    function isodd(element, index, array) 
    {  
       return (element % 2 == 1);  
    }   
    // Driver code
    var arr = [ 11, 89, 23, 7, 98 ]; 
     
    // check for odd number 
    var value = arr.filter(isodd); 
    console.log( value );

Output
[ 11, 89, 23, 7 ]

Example 3: In this example, we will see how to use the inline callback function instead of referencing a seperate function.

JavaScript
//Driver code
var arr = [ 11, 89, 23, 7, 98 ];    
// check for odd number 
var value = arr.filter(element => element % 2 == 1); 
console.log( value );

Output
[ 11, 89, 23, 7 ]

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads