EASY
Given an integer array arr and a filtering function fn, return a filtered array filteredArr.
The fn function takes one or two arguments:
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.
接受一個整數陣列arr
和過濾函數fn
並且返回對原陣列進行過濾後的新陣列filteredArr
。
fn 函數接受一個或兩個參數:
FilteredArr
應該只包含arr
中表達式fn(arr[i], i)
計算結果為真值的元素。
請在沒有使用Array.filter()的情況下解決這個問題。
const filter=(arr,fn)=>{
let filteredArr = [];
...
return filteredArr;
}
調用fn()
結果是否為真值filteredArr
const filter=(arr,fn)=>{
let filteredArr = [];
for (let i = 0; i < arr.length; i++) {
if (fn(arr[i],i)) {
filteredArr.push(arr[i]);
}
}
return filteredArr;
}
let arr1 = [0,10,20,30];
function greaterThan10(n) { return n > 10; }
console.log(filter(arr1,greaterThan10));
//Testcase
let arr2 = [1,2,3];
function firstIndex(n, i) { return i === 0; }
console.log(filter(arr2,firstIndex));
let arr3 = [-2,-1,0,1,2];
function plusOne(n) { return n + 1 }
console.log(filter(arr3,plusOne));