Iterative Methods in Javascript array
Description
Javascript array has five iterative methods.
- every() - Runs a function on every item and returns true if the function returns true for every item.
- filter() - Runs a function on every item and returns an array of all items for which the function returns true.
- forEach() - Runs a function on every item . No return value.
- map() - Runs a function on every item and returns the result in an array.
- some() - Runs a function on every item and returns true if the function returns true for any one item.
Each of the methods accepts two arguments:
- a function to run
- an optional scope object in which to run the function changing the value of
this
.
The function passed into will receive three arguments:
- the array item value,
- the position of the item in the array, and
- the array object itself.
These methods do not change the values contained in the array.
Example
var numbers = [1,2,3,4,5,4,3,2,1];
// ww w .ja v a 2s. co m
var everyResult = numbers.every(function(item, index, array){
return (item > 2);
});
console.log(everyResult); //false
var someResult = numbers.some(function(item, index, array){
return (item > 2);
});
console.log(someResult); //true
var filterResult = numbers.filter(function(item, index, array){
return (item > 2);
});
console.log(filterResult); //[3,4,5,4,3]
var mapResult = numbers.map(function(item, index, array){
return item * 2;
});
console.log(mapResult); //[2,4,6,8,10,8,6,4,2]
numbers.forEach(function(item, index, array){
console.log(item);
console.log(index);
});
The code above generates the following result.