Computer >> Computer tutorials >  >> Programming >> Javascript

How to check whether provided elements in an array have passed a specified condition or not in JavaScript?


There are two methods to check whether provided elements of an array have passed a test or not. They are Array.filter() method and _.filter() method. The former is a normal javascript method whereas the latter is a method from underscore.js, which is a library of javascript.

syntax

_.filter( list, conditions);

 This method accepts two parameters. One is the list in which the elements will be provided and the other conditions (nothing but a code).

Example

In the following example, the multiples of three were displayed using _.filter(). Here the _.filter() method has taken two parameters, one is the list and the other is the conditions.

<html>
<body>
<script type="text/javascript" src=
   "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
</script>
</head>
<body>
<script>
   var arr = [3,4,5,6,9,77,36,42]
   var threeMul = _.filter(arr,
   function(num){
      return num % 3 == 0;
   });
   document.write(threeMul);
</script>
</body>
</html>

Output

3,6,9,36,42


Array.filter()

This is a normal javascript method. This is used to filter the values whether they have passed a provided test or not. 

Example

In the following example, the salaries which are greater than a specific salary are displayed as shown in the output.

<html>
<body>
<p id="filter"></p>
<script>
   var salary = [12000, 13000, 15000, 78000, 43000];
   var specSal = salary.filter(myFunction);
   document.getElementById("filter").innerHTML = specSal;
   function myFunction(value, index, array) {
      return value > 20000;
   }
</script>
</body>
</html>

Output

78000,43000