filter callback function

filter

Filter is also a common operation. It is used to filter out some elements of Array and return the remaining elements.

Like map(), Array's filter() takes a function. Unlike map(), filter() applies the incoming function to each element in turn, and then decides whether to keep or discard the element based on whether the return value is true or false.

For example, in an Array, delete even numbers and keep only odd numbers. You can write as follows:

1 var arr = [1, 2, 4, 5, 6, 9, 10, 15];
2 var r = arr.filter(function (x) {
3     return x % 2 !== 0;
4 });
5 r; // [1, 5, 9, 15]

To delete an empty string in an Array, you can write as follows:

1 var arr = ['A', '', 'B', null, undefined, 'C', '  '];
2 var r = arr.filter(function (s) {
3     return s && s.trim(); // Note: there is no trim() method in versions below IE9
4 });
5 r; // ['A', 'B', 'C']

It can be seen that the key to using filter() as a high-order function is to correctly implement a "filter" function.

Callback function

The callback function received by filter() can have multiple parameters. Usually we only use the first parameter to represent an element of Array. The callback function can also receive two other parameters, indicating the location of the element and the Array itself:

1 var arr = ['A', 'B', 'C'];
2 var r = arr.filter(function (element, index, self) {
3     console.log(element); // Print 'A', 'B', 'C' in sequence
4     console.log(index); // Print 0, 1, 2 in turn
5     console.log(self); // self is the variable arr
6     return true;
7 });

With the help of filter, the repeated elements of Array can be removed skillfully:

1 'use strict';
2 
3 var  r;
5  var    arr = ['apple', 'strawberry', 'banana', 'pear', 'apple', 'orange', 'orange', 'strawberry'];
6 r = arr.filter(function (element, index, self) {
7     return self.indexOf(element) === index;
8 });
9 console.log(r.toString());

Operation result:

apple,strawberry,banana,pear,orange

To remove the duplicate elements, indexOf always returns the position of the first element. The position of the subsequent duplicate elements is not equal to the position returned by indexOf, so it is filtered out by the filter.

Try to filter out prime numbers with filter():

 1 'use strict';
 2 
 3 function get_primes(arr) {
 4     var i;
 5     return arr.filter(function (element) {  
 6             var flag=true;  
 7             if(element<2){  
 8             flag=false;  
 9         }else {  
10             for(var i=2;i<element;i++){  
11                 if (element%i==0){  
12                     flag=false;  
13                     break;  
14                 }  
15             }  
16         }  
17         return flag;  
18     });
19 }
20 
21 // Test:
22 var
23     x,
24     r,
25     arr = [];
26 for (x = 1; x < 100; x++) {
27     arr.push(x);
28 }
29 r = get_primes(arr);
30 if (r.toString() === [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97].toString()) {
31     console.log('Test pass!');
32 } else {
33     console.log('Test failure: ' + r.toString());
34 }

Operation result:

Test passed!

Posted by Rhysickle on Thu, 28 Nov 2019 07:44:25 -0800