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
EasyCreate a function called filterBooks that takes two parameters:
- An array of book objects, where each book has properties
title(string),author(string), andrating(number from 1 to 5) - 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
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys