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, 15];2 var r = arr.filter (function (x) {3 return x% 2!== 0;4}); 5 r;//[1, 5, 9, 15]
Delete the Array
empty string in one, so you can write:
1 var arr = [' A ', ' ', ' B ', null, undefined, ' C ', ' ];2 var r = Arr.filter (function (s) {3 return s && s) . Trim (); Note: The following version of IE9 does not have trim () Method 4}); 5 R; [' A ', ' B ', ' C ']
filter()
the key to using this higher-order function is to implement a "filter" function correctly.
callback function
filter()
The received callback function can actually have multiple parameters. Usually we use only the first parameter, which represents an Array
element. 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 (element, index, self) {3 console.log (element);////////print ' A ' in sequence, ' B ', ' C ' 4 console.log (index);///Print 0, 1, console.log (self);//Self is the variable arr6 return true;7});
Using filter
, can subtly remove Array
the repeating elements:
1 ' use strict '; 2 3 var4 r,5 arr = [' Apple ', ' strawberry ', ' banana ', ' pear ', ' apple ', ' orange ', ' orange ', ' STRAWB Erry '];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 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 { ten for (var i=2;i<element;i++) { one if (element%i==0) { flag= false; Break ; +} (+} ) + return flag; 19}20 21//test: Var23 x,24 r,25 arr = [];26 for (x = 1; x < n + +) { Arr.push (x) ;}29 r = get_primes (arr); if (r.tostring () = = = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 6 7, 97].tostring, he, I, ()) { console.log (' Test pass! '); + Else { console.log (' Test failed: ' + r.tostring ()); 34}
Operation Result:
Test pass!
Use of filter in JavaScript