Map()
We’ll start off with the map() method which can be used to apply a function to each element of the array. It takes a function as an argument which will be applied to the elements of the array:
let numSquare = num.map(element => element * element);
console.log(numSquare);
If we had done the same thing using loops then the code would have looked something like this:
for(let i = 0; i <6; i++)
{
num[i] *= num[i];
}
console.log(num);
Reduce()
The reduce() method can be used to reduce all of the values present inside the array into a single value. Following code applies reduce method on an array to get the sum of the whole array:
{
return result + element;
}
let num = [0, 1, 2, 3, 4, 5];
let sum = num.reduce(sumArray);
console.log(sum);
This can also be done with loops in the following way:
let sum = 0;
for(let i = 0; i <6; i++)
{
sum+=num[i];
}
console.log(sum);
Filter()
The filter() method can be used to apply a certain condition on the elements of an array and then get only those elements which pass that condition. Similar to the previous two methods, filter() also takes an argument function. This function is used to apply the condition on each element and then add it to an array if it passes the condition. This array will be returned by the filter method:
Consider the following code which checks whether the array contains any multiples of 5:
let multiples = num.filter(element => element % 5 == 0);
console.log(multiples);
As with the previous two methods, filter() can also be replaced with loops but with loops the code won’t be as easy to read.
Conclusion
This in-depth guide has explained the use of map(), reduce and filter methods. These functions save a ton of time and make code elegant and easier to read. The developers can use these methods to transform the data in their arrays without writing complex loops.