Array.prototype.filterLoading saved progress…

Array.prototype.filter

You reach for Array.prototype.filter every time you want a smaller array that contains only the elements matching some condition — the unread messages, the in-stock products, the users over 18. Reimplementing it forces you to think about exactly what filter does on each step and what it hands the callback.

Implement arrayFilter(arr, predicate) as a standalone function. Walk the array once. For every element, call predicate(element, index, arr) — exactly those three arguments, in that order — and keep the element only when the return value is truthy. Return a brand-new array; never mutate the input.

Signature

function arrayFilter(arr, predicate) {
  // returns a new array containing every element of `arr`
  // for which predicate(element, index, arr) is truthy.
}

Examples

arrayFilter([1, 2, 3, 4, 5], (n) => n % 2 === 0);
// [2, 4]

arrayFilter(['apple', 'fig', 'banana'], (s) => s.length > 3);
// ['apple', 'banana']
// The predicate receives (element, index, array).
arrayFilter(['a', 'b', 'c', 'd'], (_, i) => i % 2 === 0);
// ['a', 'c']

// Truthy / falsy, not strictly boolean.
arrayFilter([0, 1, '', 'hi', null, 7], (x) => x);
// [1, 'hi', 7]

Notes

  • Predicate arguments — the callback is invoked with (element, index, array). Skipping the second or third argument is a real-world bug; tests check it.
  • Truthy, not boolean — keep an element when predicate(...) is truthy. 0, '', null, undefined, NaN, and false are all dropped.
  • Don't mutate the input array, and don't reuse it as the return value. Always return a fresh array — arrayFilter(arr, () => true) should produce a new array equal in contents but !== to arr.
  • Empty input returns an empty array. The predicate is never called.
  • Holes in sparse arrays (e.g. [1, , 3]) — the real spec skips them. For this question you may either skip or visit holes; tests don't pin this down, but the solution explains the trade-off.
Loading editor…