Java Reference
In-Depth Information
The first argument, callback , is a function that is called for each element in the
array; the function is passed three arguments: the value of the element, the index of the
element, and the array itself. The returned value from the function is the element of the
new (mapped) array. The second argument is used as the this value in the function
invocation. The following is an example of using the map() method. It maps each element
of a number array to their squares:
var nums = [1, 2, 3, 4, 5];
// Map each element in the nums array to their squares
var squaredNums = nums.map(function (value, index, data) value * value);
print(nums);
print(squaredNums);
1,2,3,4,5
1,4,9,16,25
The filter() method returns a new array containing the elements of the original
array that pass a predicate. Its signature is:
filter(callback, thisArg)
The first argument, callback , is a function that is called for each element in the
array; the function is passed three arguments: the value of the element, the index of the
element, and the array itself. If the function returns a truthy value, the element is included
in the returned array; otherwise, the element is excluded. The second argument is used
as the this value in the function invocation. The following code shows how to use the
filter() method to filter out even numbers from an array:
var nums = [1, 2, 3, 4, 5];
// Filter out even numbers, keep odd numbers only
var oddNums = nums.filter(function (value, index, data) (value % 2 !== 0));
print(nums);
print(oddNums);
1,2,3,4,5
1,3,5
Search WWH ::




Custom Search