ECMAScript defines five iterative methods for arrays.
Each of the methods accepts two arguments: a function to run on each item and an optional scope object in which to run the function.
The function passed into one of these methods will receive three arguments:
Depending on the method, the results of this function's execution may or may not affect the method's return value.
The iterative methods are as follows:
Method | Description |
---|---|
every() | Runs the given function on every item in the array and returns true if the function returns true for every item. |
filter() | Runs the given function on every item in the array and returns an array of all items for which the function returns true. |
forEach() | Runs the given function on every item in the array. This method has no return value. |
map() | Runs the given function on every item in the array and returns the result of each function call in an array. |
some() | Runs the given function on every item in the array and returns true if the function returns true for any one item. |
These methods do not change the values contained in the array.
every() and some() both query the array for items matching some criteria.
For every(), the passed-in function must return true for every item in order for the method to return true; otherwise, it returns false.
The some() method returns true if even one of the items causes the passed-in function to return true.
var numbers = [1,2,3,4,5,4,3,2,1]; var everyResult = numbers.every(function(item, index, array){ return (item > 2); });/*w w w . j a v a 2 s . c om*/ console.log(everyResult); //false var someResult = numbers.some(function(item, index, array){ return (item > 2); }); console.log(someResult); //true
filter() uses the given function to determine if an item should be included in the array that it returns.
To return an array of all numbers greater than 2,
var numbers = [1,2,3,4,5,4,3,2,1]; var filterResult = numbers.filter(function(item, index, array){ return (item > 2); });//from ww w . j a v a 2 s . c om console.log(filterResult); //[3,4,5,4,3]
map() method returns an array.
Each item in the array is the result of running the passed-in function on the original array item in the same location.
For example, you can multiply every number in an array by two and are returned an array of those numbers:
var numbers = [1,2,3,4,5,4,3,2,1]; var mapResult = numbers.map(function(item, index, array){ return item * 2; });//from w w w .j a va 2s. c o m console.log(mapResult); //[2,4,6,8,10,8,6,4,2]
forEach() runs the given function on every item in an array.
There is no return value and is essentially the same as iterating over an array using a for loop.
var numbers = [1,2,3,4,5,4,3,2,1]; numbers.forEach(function(item, index, array){ //do something here });