|
| 1 | +// Question Link: https://leetcode.com/problems/filter-elements-from-array/description/?envType=study-plan-v2&envId=30-days-of-javascript |
| 2 | +// Solution Link: https://leetcode.com/problems/filter-elements-from-array/solutions/5434736/2-javascript-easy-solution-using-for-loop-and-foreach-loop/ |
| 3 | + |
| 4 | +/* |
| 5 | +2634. Filter Elements from Array |
| 6 | +
|
| 7 | +Given an integer array arr and a filtering function fn, return a filtered array filteredArr. |
| 8 | +The fn function takes one or two arguments: |
| 9 | +arr[i] - number from the arr |
| 10 | +i - index of arr[i] |
| 11 | +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. |
| 12 | +
|
| 13 | +Please solve it without the built-in Array.filter method. |
| 14 | +
|
| 15 | +Example 1: |
| 16 | +Input: arr = [0,10,20,30], fn = function greaterThan10(n) { return n > 10; } |
| 17 | +Output: [20,30] |
| 18 | +Explanation: |
| 19 | +const newArray = filter(arr, fn); // [20, 30] |
| 20 | +The function filters out values that are not greater than 10 |
| 21 | +Example 2: |
| 22 | +Input: arr = [1,2,3], fn = function firstIndex(n, i) { return i === 0; } |
| 23 | +Output: [1] |
| 24 | +Explanation: |
| 25 | +fn can also accept the index of each element |
| 26 | +In this case, the function removes elements not at index 0 |
| 27 | +Example 3: |
| 28 | +Input: arr = [-2,-1,0,1,2], fn = function plusOne(n) { return n + 1 } |
| 29 | +Output: [-2,0,1,2] |
| 30 | +Explanation: |
| 31 | +Falsey values such as 0 should be filtered out |
| 32 | + |
| 33 | +Constraints: |
| 34 | +0 <= arr.length <= 1000 |
| 35 | +-10^9 <= arr[i] <= 10^9 |
| 36 | +*/ |
| 37 | + |
| 38 | + |
| 39 | + |
| 40 | +/** |
| 41 | + * @param {number[]} arr |
| 42 | + * @param {Function} fn |
| 43 | + * @return {number[]} |
| 44 | + */ |
| 45 | + |
| 46 | +// 1st Approch: Using for Loop - TC = O(n), SC = O(n) |
| 47 | +/* |
| 48 | +var filter = function(arr, fn) { |
| 49 | + let filteredArr = []; |
| 50 | + let x = 0; |
| 51 | +
|
| 52 | + for (let i = 0; i < arr.length; i++) { |
| 53 | + if (fn(arr[i], i)) { |
| 54 | + // filteredArr.push(arr[i]); |
| 55 | + filteredArr[x++] = arr[i]; |
| 56 | + } |
| 57 | + } |
| 58 | +
|
| 59 | + return filteredArr; |
| 60 | +}; |
| 61 | +*/ |
| 62 | + |
| 63 | +// 2nd Approach: Using forEach Loop - TC = O(n), SC = O(n) |
| 64 | +var filter = function(arr, fn) { |
| 65 | + let filteredArr = []; |
| 66 | + |
| 67 | + arr.forEach((val, index) => { |
| 68 | + if (fn(val, index)) { |
| 69 | + filteredArr.push(val); |
| 70 | + } |
| 71 | + }); |
| 72 | + |
| 73 | + return filteredArr; |
| 74 | +}; |
0 commit comments