Co je filtr?
Jak funguje filtr?
Syntaxe
Funkce šipky
filter((element) => { ... } )
filter((element, index) => { ... } )
filter((element, index, array) => { ... } )
Funkce Inline Callback
filter(function callbackFn(element) { ... })
filter(function callbackFn(element, index) { ... })
filter(function callbackFn(element, index, array){ ... })
callbackFn
:
toto je funkce, která vyhodnocuje element
předáno. Vrátí true
nebo false
pro element
podle toho, zda podmínku splňují nebo nesplňují.
přijímá 3 argumenty:
element
:Aktuální prvek zpracovávaný v poli.index
(volitelné):Index aktuálního prvku zpracovávaného v poli.array
(volitelné):Byl vyvolán filtr pole.
Příklady
Příklad 1.
const names = ['judy', 'joey', 'devon', 'charlie', 'sanjay']
let jNames = names.filter(name => name.indexOf('j') >= 0)
console.log(jNames);
//expected output: ['Judy,'Joey','Sanjay']
Příklad 2
const vegis = ['tomato', 'garlic', 'green onion', 'asparagus', 'avocado']
let shortVegi = vegi.filter(vegetable => vegi.length() < 7)
console.log(shortVegetables)
//expected output: ['tomato', 'garlic']