Reading Assignment - Map, Filter and Reduce-2691
Reading Assignment - Map, Filter and Reduce-2691
There are many useful built-in methods available in JavaScript to work with arrays.
● The array.map() method allows you to iterate over an array and modify its
elements using a specified function.
● array.map () method does not modify the original array. It returns a new array
value.
For example,
let arr = [2,3, 4, 5, 6];
But you can use the array.map() method to achieve the same result.
Here's an example:
Reduce Method
● The reduce() method aims to combine the elements in a sequence and give
us a reduced single value output.
Syntax:
array.reduce(function, initialVal)
The first argument of the reduce function is called a reducer function, and the second
argument is an optional initial value.
In the parameter, the first one is the accumulator, which accumulates the results of
the execution from the reducer function and the second is the current element in the
array.
We have to calculate the sum of all elements in the array. The reducer function
executes every element of the array. Each time the reducer function executes, the
result is stored in the accumulator. At last the final single value of the accumulator is
returned once all the elements in the array are traversed.
Suppose the initial value is not supplied as an argument to the reduce() method. In
that case, the accumulator takes the first element in the array, which becomes the
accumulator's initial value, and the second element of the array will be the current
value.
We called the reduce() method and only passed the first argument, the reducer
function. Since there is no initial value, the accumulator grabs the first element in the
array to start with, 200. The second element in the array is 450, which is the current
value. The reducer function starts executing from the array's second element. It
returns the result of 650 after execution, which is the sum of the accumulator and the
current value. The accumulator will start accumulating the result. When all the
elements in the array are finished, a single value output is returned, totalling 2,805.
Using reduce() with initialValue 0
Now we will solve the same problem, but this time with an initial value, we call the
reduce() method on the array. The accumulator starts with the initial value, and the
current value is the first value in the array, which is 200. We also added the second
argument, the initial value, which is zero. This time execution of the reducer function
starts from the first element in the array. It calculates and returns the sum of the
accumulator and current value, which is zero plus 200, and from here onwards, the
accumulator starts accumulating the return values for further executions.
Finally, after traversing all the elements inside the salaries array, an output of 28,05
is returned.
Filter Method