Книга: Functional Programming in JavaScript
Назад: Array.prototype.map()
Дальше: Array.prototype.reduce()

Array.prototype.filter()

The function is used to take elements out of an array. The callback must return (to include the item in the new array) or (to drop it). Something similar could be achieved by using the function and returning a value for items you want dropped, but the function will delete the item from the new array instead of inserting a value in its place.

Note

Syntax:

Parameters:

  • : This function is used to test each element in the array. Return to keep the element, otherwise. With these parameters:
    • : This parameter gives the current element being processed in the array
    • : This parameter gives the index of the current element in the array
  • : This parameter gives the array being processed.
  • : This function is optional. Value is used as when executing .

Examples:

var myarray = [1,2,3,4] words = 'hello 123 world how 345 ya doing'.split(' '); re = '[a-zA-Z]'; // remove all negative numbers console.log([-2,-1,0,1,2].filter(function(x){return x>0})); // remove null values after a map operation console.log(words.filter(function(s){   return s.match(re); }) ); // remove random objects from an array console.log(myarray.filter(function(){   return Math.floor(Math.random()*2)}) );
Назад: Array.prototype.map()
Дальше: Array.prototype.reduce()

bsn
thank
Vesa Karvonen
I hope you don't mind, but I’d like to point you and your readers to my high-performance optics library for JavaScript that is in production use in multiple projects, has comprehensive support for partial optics and interactive documentation: https://calmm-js.github.io/partial.lenses/ (this takes a moment to load — be patient!)