2634. Filter Elements from Array
Tags
- Basic Array Transformations
Link
Question
Given an integer array
arr
and a filtering functionfn
, return a filtered arrayfilteredArr
.The
fn
function takes one or two arguments:
arr[i]
- number from thearr
i
- index ofarr[i]
filteredArr
should only contain the elements from thearr
for which the expressionfn(arr[i], i)
evaluates to a truthy value. A truthy value is a value whereBoolean(value)
returnstrue
.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
Constraints:
0 <= arr.length <= 1000
10
9<= arr[i] <= 10
9
Answer
JavaScript
/**
* @param {number[]} arr
* @param {Function} fn
* @return {number[]}
*/
var filter = function (arr, fn) {
const newArr = [];
arr.forEach((arr, i) => {
if (fn(arr, i)) newArr.push(arr);
});
return newArr;
};
/**
* @param {number[]} arr
* @param {Function} fn
* @return {number[]}
*/
var filter = function (arr, fn) {
let retArray = [];
for (let i = 0; i < arr.length; i++) {
if (fn(arr[i], i)) {
retArray.push(arr[i]);
}
}
return retArray;
};