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

Popular posts from this blog

3Sum Closest: O(n²) Two-Pointer Magic šŸš€ leetcode: 16

Kadane's Algorithm: Maximum Subarray Problem - LeetCode(53) Solution

14. Longest Common Prefix