← 返回首页
Filter through function
EN

We want to make this open-source project available for people all around the world.

Help to translate the content of this tutorial to your language!

    Search
    Search
    Light themeDark theme
    عربيDanskEnglishEspañolفارسیFrançaisIndonesiaItaliano日本語한국어РусскийTürkçeУкраїнськаOʻzbek简体中文
    back to the lesson

    Filter through function

    importance: 5

    We have a built-in method arr.filter(f) for arrays. It filters all elements through the function f. If it returns true, then that element is returned in the resulting array.

    Make a set of “ready to use” filters:

    • inBetween(a, b) – between a and b or equal to them (inclusively).
    • inArray([...]) – in the given array.

    The usage must be like this:

    • arr.filter(inBetween(3,6)) – selects only values between 3 and 6.
    • arr.filter(inArray([1,2,3])) – selects only elements matching with one of the members of [1,2,3].

    For instance:

    /* .. your code for inBetween and inArray */ let arr = [1, 2, 3, 4, 5, 6, 7]; alert( arr.filter(inBetween(3, 6)) ); // 3,4,5,6 alert( arr.filter(inArray([1, 2, 10])) ); // 1,2

    Open a sandbox with tests.

    solution
    Filter inBetween

    Filter inBetween

    function inBetween(a, b) { return function(x) { return x >= a && x <= b; }; } let arr = [1, 2, 3, 4, 5, 6, 7]; alert( arr.filter(inBetween(3, 6)) ); // 3,4,5,6
    Filter inArray

    Filter inArray

    function inArray(arr) { return function(x) { return arr.includes(x); }; } let arr = [1, 2, 3, 4, 5, 6, 7]; alert( arr.filter(inArray([1, 2, 10])) ); // 1,2

    Open the solution with tests in a sandbox.