We will be learning the map, filter and reduce functions.
- Map: The
method creates a new array with the results of calling a provided function on every element in the calling or existing array. We have to supply array, runs that through a function (which can be used to perform certain operations on the supplied array – such as, for example, converting each array item value to upper case) and subsequently returns a new array once completed.
In the second example, we are creating a new array to containing only countries name from existing array as follow.
Filter: The method
creates a new array with all elements that pass the test implemented by the provided function.
Syntax : var newArray = arr.filter(callback[, thisArg])
When using the map method to create new arrays every value from the original array is mapped to the new array. As useful as this is there are times when you only want to retrieve specific values from an array. Using the filter method values can be retrieved if they meet specific criteria. Let’s take our previous example and use the filter method to only return every 4th item from the associative array:
In the third example, we can also combine the filter and map methods for the above examples so we end up with an array populated solely with the names of every 4th company like so:
Reduce(): The reduce() method applies a function to an accumulator and each element in the array (from left to right) to reduce it to a single value. Syntax :
The reduce method accepts two parameters; first is the callback function, which is applied to each element of the array, and the second one is the initial value of the accumulator.
The reduce executes the callback function once for each element present in the array, excluding holes in the array, receiving four arguments: accumulator, currentValue, currentIndex and array. accumulator
The accumulator accumulates the callback’s return values; it is the accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied (see below).
The currentValue: The current element being processed in the array.
The currentIndex : The index of the current element being processed in the array. Starts at index 0, if an initialValue is provided, and at index 1 otherwise.
The array: The array reduce was called upon.
Example one: simple reduce function to calculate the sum of all the array element.
Example 2: Here we are using most of the callback argument, where html argument is an accumulator, the task is existing an array where we are performing reduce function and index is an index of task array.