keepcalculator

06 Numbers and Powers

Filter Function Basic Example: How It Works

Card No. 06·51259 · Updated · Standard formula, shown below

The calculator on this card is switched off while it is checked. The formula is below, and the worked example shows how to do the sum by hand.

The filter function is a programming tool that takes an array (or list) and returns a new array containing only the elements that pass a test you provide. You give it two things: the array to examine and a callback function that returns true or false for each element. The result is a new array with the elements where the callback returned true, leaving the original array unchanged.

Formula

The filter function does not have a mathematical formula; it is a higher-order function that applies a predicate to each element. In pseudo-code:

filter(array, predicate) = new array containing each element e where predicate(e) is true

Where:

  • array is the original list of items (numbers, strings, objects, etc.).
  • predicate is a function that takes one element and returns a boolean (true or false).
  • new array is the output; it preserves the order of the original array and has the same length or shorter.

In JavaScript, the syntax is array.filter(callback). In Python, it is filter(callback, array). In most languages, the original array is not modified.

Worked Example

Using the default values from the calculator above: input array is 1, 2, 3, 4, 5, 6 and the test is to keep values greater than 3.

  1. Start with the first element: 1. Is 1 > 3? No, so exclude it.
  2. Next element: 2. Is 2 > 3? No, exclude.
  3. Next: 3. Is 3 > 3? No (strictly greater), exclude.
  4. Next: 4. Is 4 > 3? Yes, include.
  5. Next: 5. Is 5 > 3? Yes, include.
  6. Next: 6. Is 6 > 3? Yes, include.

The filtered array is [4, 5, 6].

How the Filter Function Works Internally

Behind the scenes, the filter function iterates over each element of the array, calls the callback with that element (and optionally its index and the whole array), and checks the returned value. If the value is truthy (in JavaScript, any value that is not false, 0, "", null, undefined, or NaN), the element is pushed to a new array. If falsy, it is skipped. The iteration stops when the end of the array is reached, and the new array is returned.

This is a pure function in functional programming: it does not mutate the original array, and it always returns a new array. Most modern languages implement filter with optimizations, but the behavior is consistent across them.

Common Use Cases for Filter

Filter is used whenever you need to extract a subset of data that meets certain criteria. Common examples include:

  • Removing null or undefined values from an array.
  • Selecting products with a price below a threshold.
  • Filtering a list of users by age or membership status.
  • Finding even numbers from a list of integers.
  • Removing duplicate values (combined with a Set or indexOf check).

In data analysis, filter is often used to clean datasets before aggregation. In web development, it is used to display search results, sortable tables, or to implement client-side search filters.

How to Choose the Right Callback

The callback is the heart of filter. It must be a function that returns a boolean (or a truthy/falsy value). When writing a callback, ask: “What condition must an element satisfy to be kept?” For example:

  • To keep numbers greater than 10: x => x > 10
  • To keep strings that contain the letter ‘a’: str => str.includes('a')
  • To keep objects where active is true: obj => obj.active
  • To keep non-null values: item => item !== null

Make sure the callback does not have side effects (like modifying the element) because filter should be pure. If you need to transform elements, use map after filtering.

Common Mistakes and Misconceptions

One common mistake is forgetting that filter returns a new array; the original array remains unchanged. This often surprises beginners who expect the original to be modified. Another mistake is using filter when you should use find (to get the first match) or some (to check if any element matches).

Another misconception is that filter removes elements that return false from the original array. It does not; it creates a shallow copy of the elements that pass the test. Also, if the callback returns a non-boolean value, it is coerced to truthy/falsy, which can lead to unexpected results if you return a number like 0 or an empty string.

Finally, be careful with the index parameter. If you use the index in the callback, remember that it refers to the index in the original array, not the filtered array.

Filter vs. Other Array Methods

Filter is often confused with map and reduce. Here is a quick comparison:

  • map transforms every element and returns a new array of the same length.
  • filter selects a subset and returns a new array of equal or shorter length.
  • reduce combines all elements into a single value (like a sum or object).

You can chain them: array.filter(...).map(...) is common for filtering then transforming. For example, get the names of active users: users.filter(u => u.active).map(u => u.name).

Performance and Limitations

Filter runs in O(n) time, meaning it checks each element once. For large arrays (millions of elements), this can be slow if the callback is complex. In such cases, consider using a more efficient data structure like a Set for membership tests, or pre-indexing data. Also, filter creates a new array, which uses additional memory. If you need to filter in-place (rare), you would need a manual loop.

Another limitation is that filter only works on arrays or iterables. In JavaScript, you cannot directly filter an object without converting it to an array of entries first. In Python, filter returns an iterator, not a list, so you need list(filter(...)) to get an array.

Frequently Asked Questions

Does filter change the original array?

No, filter returns a new array and leaves the original untouched. This is true in JavaScript, Python, and most other languages. If you need to modify the original, you would have to assign the result back: arr = arr.filter(...).

Can I filter an array of objects?

Yes, filter works on any array, including arrays of objects. The callback receives each object, and you can access its properties. For example, to keep products with price > 10: products.filter(p => p.price > 10).

How do I filter out null or undefined values?

Use a callback that checks for null and undefined: arr.filter(item => item != null) (loose inequality) or item !== null && item !== undefined. In JavaScript, you can also use Boolean as the callback to remove all falsy values, but that also removes 0 and empty strings.

What is the difference between filter and find?

Filter returns an array of all matching elements. Find returns only the first matching element (or undefined if none). Use find when you expect only one match and want a single value, not an array.

Can filter be used on strings?

In most languages, filter works on arrays, not strings directly. However, you can split a string into an array of characters, filter, and join back. For example, to remove vowels: str.split('').filter(c => !'aeiou'.includes(c)).join('').

Does filter work in all programming languages?

Most modern languages have a filter function or method: JavaScript (Array.prototype.filter), Python (filter built-in), Java (Stream.filter), C# (Where in LINQ), Ruby (select), and many others. The concept is universal, though syntax varies.

Related

Formula used
in arr | Input array (comma-separated) | - | 1, 2, 3, 4, 5, 6 | 0 | 1000
in test | Test: keep values greater than | - | 3 | 0 | 1000
out filtered | Filtered array | - | arr.split(',').map(Number).filter(x => x > test).join(', ') | 0

Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →