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.
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.
<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>
So, we have an Array that has 5 numbers.
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.
And the new array is printed as output.
5,8,2,9