Codectionary / Developer documentation / JavaScript

filter()

filter() builds a new array of items that pass your test, in their original order. Use it to show only unfinished lessons or available products. If nothing matches, you receive an empty array. The new array contains the existing values; objects inside it are not cloned.

Syntax

items.filter((item, index, array) => condition)

Examples

Choose lessons to study next

Select unfinished lessons first, then turn them into a list of titles.

const lessons = [
  { title: "Arrays", completed: false },
  { title: "Variables", completed: true },
  { title: "Functions", completed: false }
];
const next = lessons.filter(lesson => !lesson.completed);
console.log(next.map(lesson => lesson.title)); // ["Arrays", "Functions"]
console.log(lessons.filter(lesson => lesson.title === "Loops")); // []

Remove missing scores without losing zero

filter(Boolean) would also remove 0. Check specifically for null and undefined when zero is a valid score.

const scores = [0, null, 8, undefined, 10];
const recorded = scores.filter(score => score !== null && score !== undefined);
console.log(recorded); // [0, 8, 10]
console.log(scores.filter(Boolean)); // [8, 10]

A new array can still share objects

Changing a retained object is visible through the original array too. Create a new object with map() when you want to change a value independently.

const lessons = [{ title: "Arrays", completed: false }];
const selected = lessons.filter(lesson => !lesson.completed);
console.log(selected === lessons); // false
console.log(selected[0] === lessons[0]); // true
const completed = selected.map(lesson => ({ ...lesson, completed: true }));
console.log(completed[0].completed); // true
console.log(lessons[0].completed); // false

Parameters and values

  • callback: Receives the current item, its index and the original array. Return a truthy value to keep that item, or a falsy value to exclude it. Empty slots are skipped.
  • Return value: A new array containing the selected items. filter() itself does not change the input array, but a callback can still mutate it or its objects.
  • thisArg (optional): A second argument sets this for a regular callback function, but not for an arrow function.

Best practices

  • Use find() for one match or some() for a yes/no answer; there is no need to build a filtered array for those questions.
  • Return the condition explicitly when the callback has braces. Without return, each result is undefined and nothing is kept.
  • Do not pass an async predicate: Promises are truthy, so filter() will keep items without waiting for the checks.

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

Specifications & further reading