Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   




filter() - FUNCTION


filter() Function is used to create an array with those elements that satisfies a given condition.


Let us say, we have a Array that contains five numbers, 5, 8, 2, 81 and 9.

java_Collections

And we want to have an array with only those elements those are less than 10.


And filter() gives us an elegant way to do it.


Let us see in the below example.


Example :



<html>
<body>  
<script>

	function numberCheck(i) {
  		return i < 10
	}

	var x = [5, 8, 2, 81, 9]
	var y = x.filter(numberCheck)
	
    document.write(y)
	    
</script>      
</body>
</html>


Output :



  5,8,2,9

So, we have an Array that has 5 numbers.

java_Collections

And we want to construct an array with only those elements those are less than 10.


We have defined a function called numberCheck(), that checks if a number is less than 10.


function numberCheck(i) {
	return i < 10
}

And we have called the above function from filter() function.


var y = x.filter(numberCheck)

And filter() function iterates 5 times(i.e. The length of the array), calling numberCheck() function.


var y = x.filter(numberCheck)

And it only picks those values, which are less than 10 and forms a new Array.

java_Collections

And the new array is printed as output.


5,8,2,9