1 The `filter()` function filters the given array by invoking the specified 2 callback for each item of the input array and only keeping items for which 3 the callback returned a truish value. 4 5 Returns the filtered copy of the input array, maintaining the original order 6 of items. The input array is not modified. 7 8 Returns `null` if the first argument is not an array. 9 10 -- Testcase -- 11 {% 12 let numbers = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]; 13 14 printf("%.J\n", 15 filter(numbers, function(n) { 16 return (n % 2) == 0; 17 }) 18 ); 19 %} 20 -- End -- 21 22 -- Expect stdout -- 23 [ 24 0, 25 2, 26 4, 27 6, 28 8 29 ] 30 -- End -- 31 32 33 Supplying an invalid callback will trigger an exception. 34 35 -- Testcase -- 36 {% 37 filter([1, 2, 3], "not_a_function") 38 %} 39 -- End -- 40 41 -- Expect stderr -- 42 Type error: left-hand side is not a function 43 In line 2, byte 36: 44 45 ` filter([1, 2, 3], "not_a_function")` 46 Near here ----------------------------^ 47 48 49 -- End -- 50 51 52 Supplying an invalid array will yield `null`. 53 54 -- Testcase -- 55 {% 56 printf("%.J\n", filter("not_an_array", function(i) { return i > 3 })); 57 %} 58 -- End -- 59 60 -- Expect stdout -- 61 null 62 -- End -- 63 64 65 The callback is invoked with three argument for each item, the current item 66 value, the index position of the item and the input array being mapped. 67 68 -- Testcase -- 69 {% 70 let words = [ "foo", "bar", "baz", "qrx" ]; 71 72 print(join("\n", 73 filter(words, function(word, idx, src) { 74 printf("word=%s, idx=%d, src=%J\n", word, idx, src); 75 76 return true; 77 }) 78 ), "\n"); 79 %} 80 -- End -- 81 82 -- Expect stdout -- 83 word=foo, idx=0, src=[ "foo", "bar", "baz", "qrx" ] 84 word=bar, idx=1, src=[ "foo", "bar", "baz", "qrx" ] 85 word=baz, idx=2, src=[ "foo", "bar", "baz", "qrx" ] 86 word=qrx, idx=3, src=[ "foo", "bar", "baz", "qrx" ] 87 foo 88 bar 89 baz 90 qrx 91 -- End -- 92 93 94 Exceptions in the callback terminate the filter process and are 95 propagated to the calling context. 96 97 -- Testcase -- 98 {% 99 filter([ 1, 2, 3 ], function() { die() }); 100 %} 101 -- End -- 102 103 -- Expect stderr -- 104 Died 105 In [anonymous function](), line 2, byte 39: 106 called from function filter ([C]) 107 called from anonymous function ([stdin]:2:42) 108 109 ` filter([ 1, 2, 3 ], function() { die() });` 110 Near here -------------------------------^ 111 112 113 -- End --
This page was automatically generated by LXR 0.3.1. • OpenWrt