Animations
API
Arrays
Async
Basics
Challenges
Classes
Console
Dates
Debugging
DOM Elements
DOM Methods
DOM Properties
Event Listeners
Flow Control
Forms
Functions
Global Functions
JSON
Keywords
Libraries (3rd party)
Math
Modules
Objects
Snippets
String
Types
Widgets
Window Object
https://www.w3schools.com/jsref/jsref_obj_array.asp
The filter()
method allows you to apply a filter to an array and then return a new
array based on the elements of the original that meet the condition. filter()
will return whatever is
in the original array whether it is a number, string, or object.
The filter()
method creates an array filled with array elements that pass a test (provided as a function).
filter()
executes on each element of the array and does not execute the function for array elements without values.
Note: filter() does not change the original array.
Example 1
const ages = [40, 11, 8, 32, 33, 16, 40];
const CheckForAdult = (age) => { return age >= 18; };
document.getElementById("demo1").innerHTML = ages.filter(CheckForAdult);
Example 2. Here's an example using a function expression. Instead of creating a separate function, were defining its definition right in the filter's argument.
const ages = [40, 11, 8, 32, 33, 16, 40];
document.getElementById("demo2").innerHTML = ages.filter((a) => a < 18 );
Example 3. Uses authors.js.
let femaleAuthors = authors.filter((author) =>
{
if (author.gender.toLowerCase() === "female")
{
return author;
}
});