Array filter() filters array with the given function.
filter() accepts two arguments:
- a function to run on each item and
- an optional scope object
filter() runs the given function on every item and returns an array of all items for which the function returns true.
The function passed in receives three arguments:
- the array item value,
- the position of the item in the array
- the array object itself.
For example, to return an array of all numbers greater than 2:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var numbers = [1,2,3,4,5,4,3,2,1];
var filterResult = numbers.filter(function(item, index, array){
return (item > 2);
});
document.writeln(filterResult); //[3,4,5,4,3]
</script>
</head>
<body>
</body>
</html>
filter() does not change the values contained in the array.
Home
JavaScript Book
Essential Types
JavaScript Book
Essential Types
Array:
- The Array Type
- Array Built-in Methods
- Detecting Arrays
- Get and set array values
- Enumerating the Contents of an Array
- Array Length
- Array join() method
- Array concat()
- Array indexOf()
- Array lastIndexOf()
- Array every()
- Array filter() filters array with the given function.
- Array map()
- Array forEach()
- push() and pop():Array Stack Methods
- push(), shift():Array Queue Methods
- Array reduce()
- Array reduceRight()
- reverse():Reordering array
- Array slice()
- Array some()
- Array splice()
- Array sort()
- toString(), toLocaleString() and valueOf Array
- Array unshift()