Explain the importance of Array.filter() method in JavaScript with example?



Array.filter()

Array.filter() method creates a new array with all the elements that have passed the test implemented by the provider function(function given by the user).In the following example the test is whether the given salary elements are more than a particular value(19000) given by the user().

Example-1

Live Demo

<html>
<body>
<p id="filter"></p>
<script>
   var salary = [2000, 30000, 69000, 70000,78000];
   function checkSal(sal) {
      return sal >= 19000;
   }
   document.getElementById("filter").innerHTML = salary.filter(checkSal);
</script>
</body>
</html>

Output

30000,69000,70000,78000

Example-2

Following is the example to filter positive values from a given integer array.

Live Demo

<html>
<body>
<script>
   var numbers = [2,3,4,5,-9,0,-2,-5]
   function Positive(value) {
      return value > 0;
   }
   var posnum = numbers.filter(Positive);
   document.write(posnum);
</script>
</body>
</html>

Output

2,3,4,5



Advertisements