Filter
Filter is also a common operation, it is used to Array
filter out some of the elements, and then return the remaining elements.
and map()
Similarly, Array
filter()
a function is also received. And the map()
difference is that the filter()
incoming function acts on each element in turn, and then whether true
false
the element is persisted or discarded based on the return value.
For example, in one Array
, delete an even number, keep only the odd number, and you can write:
1 var arr = [1, 2, 4, 5, 6, 9, ten,]; 2 var r = Arr.filter (function (x) {3 return x% 2!== 0; 4 }); 5 // [1, 5, 9, a]
Delete the Array
empty string in one, so you can write:
1 var null, Undefined, ' C ', ' ]; 2 var r = Arr.filter (function (s) {3 return// Note: The following version of IE9 does not have trim () method 4}); 5 // [' A ', ' B ', ' C ']
filter()
the key to using this higher-order function is to implement a "filter" function correctly.
callback function
The
filter ()
receives a callback function that can actually have multiple parameters. Usually we use only the first argument, which represents an element of an Array
. The callback function can also receive two additional parameters, representing the location of the element and the array itself:
1 var arr = [' A ', ' B ', ' C ' "; 2 var r = arr.filter (function 3 Console.log (Element); // print ' A ', ' B ', ' C ' in turn 4 console.log (index); // print 0, 1, 2 5 console.log (self); // 6 return True ; 7 });
Using filter
, can subtly remove Array
the repeating elements:
1 ' use strict '; 2 3 var 4 R,5 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
The removal of a repeating element relies on indexOf
always returning the position of the first element, and the subsequent repetition of the element's position is indexOf
not equal to the position returned, and is therefore filter
filtered out.
Try to filter()
filter out primes:
1' Use strict ';2 3 functionGet_primes (arr) {4 vari;5 returnArr.filter (function(Element) {6 varflag=true; 7 if(element<2){ 8flag=false; 9}Else { Ten for(vari=2;i<element;i++){ One if(element%i==0){ Aflag=false; - Break; - } the } - } - returnFlag; - }); + } - + //Test: A var at x, - R, -arr = []; - for(x = 1; x <) { - Arr.push (x); - } inR =get_primes (arr); - 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 ()) { toConsole.log (' Test pass! ')); +}Else { -Console.log (' Test failed: ' +r.tostring ()); the}
Operation Result:
Test pass!
Usage of filter in JavaScript