There are three array methods in JavaScript: map, reduce, and filter. All these functions will iterate over the array and perform the function. Each will create a new array in response to the function's output. You will discover the rationale for each one's use in this article.
map()
The map method creates a new array with the results of calling a function for every array element.
const output = arr.map(function)
this function tells about the transformation I want on each element of the array.
Let's take an example:
const arr = [6, 3, 5, 9, 2];
//if we want to double each element in the arr, we can use map
const doubleArr = arr.map(double);
//creating the function double
function double(x){
return 2 * x;
}
//the map will run double function for each element in the arr, and create a new array and returns it.
console.log(doubleArr); //[12, 6, 10, 18, 4];
So, basically map function is mapping each and every value and transforming based on the given condition.
filter()
Filter function is used to filter the value inside the array. This method also creates a new array from the given array consisting of only those elements from the given array which satisfy a condition set by the argument method.
Let's take an example:
Suppose we have given an array and we want a new array with all the elements greater than 4 for the values present in arr.
So, the ans will look like [5, 6, 9, 8]
const arr = [5, 6, 1, 4, 9, 8];
//filter values > 4
function isGreaterThan4(x){
return x > 4;
}
const arr2 = arr.filter(isGreaterThan4);
//we can also use arrow function to rewrite the same code as :
const arr2 = arr.filter((x) => x > 4);
console.log(arr2); //[5, 6, 9, 8]
reduce()
It is function which take all the values of array and gives a single output of it. It reduces the array to give a single output.
Let's take an example:
First we will find the sum of a given array using loops and then will move on to use reduce to better understand it.
const array = [5, 1, 3, 2, 6];
// Let's calculate sum of elements of array - Non functional programming way
function findSum(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum = sum + arr[i];
}
return sum; }
console.log(findSum(array)); // 17
// reduce function way
const sumOfElem = arr.reduce(function (accumulator, current) {
// current represent the value of array
// accumulator is used the result from element of array.
// In comparison to previous code snippet, *sum* variable is
*accumulator* and *arr[i]* is *current*
accumulator = accumulator + current;
return accumulator;
}, 0); //In above example sum was initialized with 0, so over here
accumulator also needs to be initialized, so the second argument to reduce
function represent the initialization value.
console.log(sumOfElem); // 17
This tweets sums the entire article:
Also, if you want a detailed explanation, do check out Namaste Javascript
Top comments (0)