Menu
Coddy logo textTech

Filter

Lesson 12 of 18 in Coddy's Array Methods in JavaScript course.

The filter() method is a built-in function for arrays that creates a new array containing only elements that pass a test implemented by a provided callback function. It iterates through each element of the original array and applies the callback function to it. If the callback function returns true for an element, that element is included in the new filtered array. Otherwise, it's excluded.

Let's imagine you have a list of movie ratings (numbers) and you want to create a new list containing only movies with ratings above 4 stars. Here's how you can use filter():

const ratings = [3.5, 4.8, 2.9, 5.0, 4.2];

// Callback function to check if rating is above 4
const goodMovies = ratings.filter(rating => rating > 4);

console.log(goodMovies); // Output: [4.8, 5.0]

In above example, The filter() method iterates through the ratings array and keeps only elements that meet the condition specified in the callback function (rating => rating > 4).

challenge icon

Challenge

Easy

An array named friends contains a list of friends and their status, respectively.

Your task is to create a new list that includes only friends who are online and make sure to log the extracted array.

Try it yourself

const friends = [
  { name: "Alice", online: true },
  { name: "Bob", online: false },
  { name: "Charlie", online: true },
  { name: "David", online: false }
];

// Write code here

All lessons in Array Methods in JavaScript