Please note that this section will contain the use of Functions. To understand it better it is advised to go through the Function section first.
filter() Method:
It is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method.
Syntax: array.filter(callback(element, index, arr), thisValue)
where,
This method returns a new array consisting of only those elements that satisfied the condition of the arg_function.
Example:
var A = [112, 52, 0, -1, 944];
var z = A.filter(isPositive);
function isPositive(value) {
return value > 0;
}
In the above example, [112,52,944] will be stored in a z array.
map() Method:
It creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method. Generally, map() method is used to iterate over an array and calling a function on every element of the array.
Syntax: array.map(callback(element, index, arr), thisValue)
where,
This method returns a new array consisting of only those elements that satisfied the condition of the arg_function.
Example:
var A = [1, 2, 3, 4];
var z = A.map(myFunction)
function myFunction(num) {
return num * 10;
}
In the above example, [10, 20, 30, 40] will be stored in a z array.
Try the following example in the editor below.
You are given array A of integers with its size. First, make a new array B after multiplying each element of the previous array by 2. Then in another array C stores elements from B only if it is divisible by 8. Finally print the array C. Please note that you have to print one element in one line. Example: Suppose A is [2,4,6,20], then B will be [4,8,12,40] and finally C will be [8,40].
Sample Input:
4(Size)
2
4
6
20
Sample Output:
8
40