[Easy] LeetCode JS 30 - 2634. Filter Elements from Array

March 5, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

LeetCode 30 Days of JavaScript

This question is from LeetCode's 30 Days of JavaScript Challenge

2634. Filter Elements from Array

Question Prompt

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

Solutions

Looking to practice more questions like these? We recommend GreatFrontEnd, the best platform for honing your frontend interview skills!

We can start by defining a function named filter that takes two parameters: arr (the array to be filtered) and fn (the callback function that defines the filtering criteria). Then, create an empty array named returnedArr  to store the filtered elements.

Use a for loop iterates over each element of the arr array. The loop variable i acts as the index counter. Inside the loop, the fn function is called with two arguments: the current element (arr[i]) and its index (i). The return value of this fn call determines the element's fate.

If the fn function returns true, it means the element passes the filter criteria. In this case, the element is pushed onto the returnedArr array.

After iterating through all elements, the filter function returns the returnedArr array, which now contains only the elements that passed the filtering condition defined by the fn function.

var filter = function (arr, fn) {
  const returnedArr = [];
  for (let i = 0; i < arr.length; i++) {
    if (fn(arr[i], i)) {
      returnedArr.push(arr[i]);
    }
  }
  return returnedArr;
};
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee