Javascript array has five iterative methods.
Each of the methods accepts two arguments:
this
. The function passed into will receive three arguments:
These methods do not change the values contained in the array.
var numbers = [1,2,3,4,5,4,3,2,1];
//from ww w . j a va2 s .c o 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.
Reduction methods iterate over all array items and return one value.
Javascript has two reduction methods:
They both accept two arguments:
The function passed into reduce() or reduceRight() accepts four arguments:
Value returned from the function is passed in as the first argument for the next item.
You can use the reduce() and reduceRight() method to perform operations such as adding all numbers in an array.
var values = [1,2,3,4,5];
var sum = values.reduce(function(prev, cur, index, array){
return prev + cur;/* w w w.j a va2 s. c o m*/
});
console.log(sum); //15
var sum = values.reduceRight(function(prev, cur, index, array){
return prev + cur;
});
console.log(sum); //15
In the code above when calling reduce(), the first time the callback function is executed, prev is 1 and cur is 2; the second time, prev is 3 resulting of adding 1 and 2, and cur is 3 which is the third item in the array.
The first iteration occurs on the second item in the array, so the first argument is the first item in the array and the second argument is the second item in the array.
The code above generates the following result.