Menu
Coddy logo textTech

The Filter Method

Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 53 of 65.

The filter() method creates a new array with all elements that pass the test implemented by the provided function. It's useful for selecting a subset of elements from an array based on certain criteria.

Basic syntax:

let newArray = arr.filter(function(currentValue, index, array) {
    // return true to keep the element, false otherwise
});

Here's a simple example:

const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4, 6]

The filter() method doesn't modify the original array. It returns a new array containing only the elements that passed the test.

challenge icon

Challenge

Easy

Create a function called filterBooks that takes two parameters:

  1. An array of book objects, where each book has properties title (string), author (string), and rating (number from 1 to 5)
  2. A minimum rating (number)

The function should use the filter() method to return a new array containing only the books with a rating greater than or equal to the minimum rating.

Cheat sheet

The filter() method creates a new array with elements that pass a test function:

let newArray = arr.filter(function(currentValue, index, array) {
    // return true to keep the element, false otherwise
});

Example filtering even numbers:

const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4, 6]

The filter() method doesn't modify the original array - it returns a new array.

Try it yourself

function filterBooks(books, minRating) {
  // Write your code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow