filter
Filter an array returning a subset of the items based on a predicate.
filter(fn)
Filter an array of items based on a function predicate.
import { ObservableArray, ObservableObject, type } from "can/everything";
class Cartoon extends ObservableObject {
static props = {
title: String,
studio: String
}
}
class Cartoons extends ObservableArray {
static items = type.convert(Cartoon);
}
let toons = new Cartoons([
{ title: "Looney Tunes", studio: "Warner Bros." },
{ title: "Darkwing Duck", studio: "Disney" },
{ title: "Merrie Melodies", studio: "Warner Bros." },
{ title: "Mickey Mouse", studio: "Disney" },
{ title: "The Flintstones", studio: "Hanna-Barbera" }
]);
let filtered = toons.filter(cartoon => cartoon.title === "The Flintstones");
console.log( filtered );
// -> [ { title: "The Flintstones", studio: "Hanna-Barbera" } ]
Parameters
- fn
{function}
:A predicate function that will be run for each item in the array. If the function returns true, the item will be included in the filtered resultset.
Returns
{ObservableArray}
:
A ObservableArray
matching the type of the original array.
filter(props)
Filter an array of items that match a subset of properties. A match will be made if any properties provided to props
are within an item.
import { ObservableArray, ObservableObject } from "can/everything";
class Cartoon extends ObservableObject {
static props = {
title: String,
studio: String
}
}
class Cartoons extends ObservableArray {
static items = Cartoon;
}
let toons = new Cartoons([
{ title: "Looney Tunes", studio: "Warner Bros." },
{ title: "Darkwing Duck", studio: "Disney" },
{ title: "Merrie Melodies", studio: "Warner Bros." },
{ title: "Mickey Mouse", studio: "Disney" },
{ title: "The Flintstones", studio: "Hanna-Barbera" }
]);
let filtered = toons.filter({ studio: "Warner Bros." });
console.log( filtered.length ); // -> 2
console.log( filtered );
Parameters
- props
{Object}
:An object of properties to be matched against.
Returns
{ObservableArray}
:
A ObservableArray
matching the type of the original array.