更新於 2024/11/02閱讀時間約 3 分鐘

2634. Filter Elements from Array

    跟前一題一樣,這題是要避免使用 Array.filter 來過濾要的元素,並回傳新的陣列

    題目:

    Given an integer array arr and a filtering function fn, return a filtered array filteredArr.

    The fn function takes one or two arguments:

    • arr[i] - number from the arr
    • i - index of arr[i]

    filteredArr should only contain the elements from the arr for which the expression fn(arr[i], i) evaluates to a truthy value. A truthy value is a value where Boolean(value) returns true.

    Please solve it without the built-in Array.filter method.

     

    Example 1:

    Input: arr = [0,10,20,30], fn = function greaterThan10(n) { return n > 10; }
    Output: [20,30]
    Explanation:
    const newArray = filter(arr, fn); // [20, 30]
    The function filters out values that are not greater than 10

    Example 2:

    Input: arr = [1,2,3], fn = function firstIndex(n, i) { return i === 0; }
    Output: [1]
    Explanation:
    fn can also accept the index of each element
    In this case, the function removes elements not at index 0

    Example 3:

    Input: arr = [-2,-1,0,1,2], fn = function plusOne(n) { return n + 1 }
    Output: [-2,0,1,2]
    Explanation:
    Falsey values such as 0 should be filtered out

     

    解題邏輯:

    跟前面一樣,我們要先把函式、迴圈,跟回傳的新陣列給寫好,

     function map(arr, fn) {
    let returnedArray=[]
    for (let i = 0; i < arr.length; i++) {}

    接著,因為要符合題目給的 Function 再取出,這次改用 if,當 Functiom 為 true 的時候再把他加到原本的 filteredArr 上。

    function filter(arr, fn) {
    let filteredArr =[];
    for (let i = 0; i < arr.length; i++) {
    if (fn(arr[i], i)) {
    filteredArr.push(arr[i]) ;
    }
    }
    return filteredArr
    }

    完成!




    分享至
    成為作者繼續創作的動力吧!
    © 2024 vocus All rights reserved.