2634. Filter Elements from Array
Intuition
Using forEach loop to access all elements from given array
Approach
create a new array pass all value of the given array to to the function if the function return true add the value into the new array
Complexity
Time complexity: O(n)
Space complexity: O(n)
Code:
/** * @param {number[]} arr * @param {Function} fn * @return {number[]} */ var filter = function(arr, fn) { let newArr = new Array(); let i = 0; arr.forEach((e , index) => { if(fn(e,index)){ newArr[i] = e; i++; } }); return newArr; };
Comments
Post a Comment