Recent Posts
Recent Comments
게으른개발너D
[Array] Filter Elements from Array (filter 구현하기) 본문
https://leetcode.com/problems/filter-elements-from-array/
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
solution
/**
* @param {number[]} arr
* @param {Function} fn
* @return {number[]}
*/
var filter = function(arr, fn) {
const answer = [];
for(i = 0; i < arr.length; i++) {
const isTrue = fn(arr[i], i);
if(isTrue) {
answer.push(arr[i]);
}
}
return answer;
};
'알고리즘 > 과제' 카테고리의 다른 글
[Promise] Promise Time Limit (feat. race) ⭐️ (0) | 2023.07.03 |
---|---|
[Array] Apply Transform Over Each Element in Array (map 구현하기) (0) | 2023.07.03 |
[Function, Closure] Function Composition (feat. reduceRight) (0) | 2023.07.03 |
[Array] Array Reduce Transformation (reduce 정의하기) (0) | 2023.07.03 |
[Promise] Sleep ⭐️ (0) | 2023.07.03 |
Comments