Magicsheet logo

Filter Elements from Array

Easy
12.5%
Updated 8/1/2025

Asked by 3 Companies

Topics

Filter Elements from Array

What is this problem about?

The Filter Elements from Array interview question is a functional programming task, usually in JavaScript. You are asked to implement a function that takes an array and a "filtering function" (callback). Your function should return a new array containing only the elements for which the filtering function returns a truthy value. This is a custom implementation of the built-in Array.prototype.filter() method.

Why is this asked in interviews?

Companies like Amazon and Google ask this to test your understanding of Higher-Order Functions and callbacks. It evaluates if you can write clean, generic code that works with logic provided by the caller. It also checks your familiarity with array iteration and memory management (creating a new array instead of modifying the original).

Algorithmic pattern used

This problem follows a simple Linear Scan with Callback pattern.

  1. Initialize an empty result array.
  2. Iterate through the input array using a for loop.
  3. For each element at index i:
    • Call the filtering function fn(arr[i], i).
    • If the result is "truthy," push arr[i] into the result array.
  4. Return the new array.

Example explanation

Array: [10, 20, 30], Filtering function: (x) => x > 15.

  1. i=0: 10 > 15 is false. Skip.
  2. i=1: 20 > 15 is true. Add 20.
  3. i=2: 30 > 15 is true. Add 30. Result: [20, 30].

Common mistakes candidates make

  • Modifying the input: Removing elements from the original array while iterating, which causes index shifting bugs.
  • Truthy vs Boolean: Not realizing that in JavaScript, values like 1, "hello", and {} are "truthy" and should be treated as true.
  • Ignoring the index: Forgetting that the filtering function often expects the index i as a second argument.

Interview preparation tip

Be ready to explain why you use a for loop instead of forEach or map. Usually, a standard for loop is preferred for custom implementations to avoid unnecessary function overhead or to allow for early exits (though filter doesn't exit early).

Similar Questions