العودة إلى الدورة

Array Selection: The filter() Method

JavaScript: الدورة الكاملة للمبتدئين من 'الصفر إلى الاحتراف'

60. Array Selection: The .filter() Method

.filter() is used to create a new array containing only the elements that pass a specific test (implemented by the provided callback function).

Syntax

The callback function must return a Boolean: true to keep the element, false to discard it.

javascript const newArray = oldArray.filter(element => { return condition; // true or false });

Example: Filtering Adult Users

javascript const people = [ { name: 'Max', age: 15 }, { name: 'Sarah', age: 25 }, { name: 'Leo', age: 40 } ];

const adults = people.filter(person => { return person.age >= 18; });

console.log(adults); // Output: [{ name: 'Sarah', age: 25 }, { name: 'Leo', age: 40 }]

Chaining Methods

Since .map() and .filter() both return new arrays, they can be chained together (e.g., first filter the data, then map the filtered results).