Data Transformations: map(),filter(),reduce()
Map, Filter and Reduce array methods in JavaScript
Introduction
Though there are many array methods in javascript then what's so special about these methods?
Map, filter, and reduce are powerful Array methods to loop over Arrays and perform a calculation on the array elements.
In this article, you will learn how to use these amazing methods on Arrays.
Example
To illustrate, consider an array containing your bank transactions, where a 1.2% tax applies to each transaction.
You need to find the following things:
Value of each transaction after interest.
Incoming transactions.
Calculate the final amount.
const transactions = [200, -100, 500, -300, 600, 700, -250];
So how can we do these?
We can use forEach loop for doing all three transformations.
Value of each transaction after interest.
We take a new array
finalTransaction
to store the value after calculating the interest.
const transactions = [200, -100, 500, -300, 600, 700, -250];
const finalTransaction = [];
//forEach loop
transaction.forEach(function (element) {
// Calculating value of each transaction after interest
element = Math.round(element + element * (5 / 100));
// Pushing each element to new Array
finalTransaction.push(element);
// Printing transaction
console.log(`FinalTransaction: ${finalTransaction}`);
}
OUTPUT:
FinalTransaction: 210,-105,525,-315,630,735,-262
We can do it in a more simplified using the map() method.
map() method
The map()
method creates a new array from the contents of the calling array after performing a given function on each element.
Syntax
map(function (element, index, array) { /* … */ })
callbackFn:
A function to execute for each element in the array. Its return value is added as a single element in the new array.
element:
The current element is being processed in the array.
index
The index of the current element being processed in the array.
array
The array on which the map()
method was called upon.
By using the map() method we can do it like this:
const FinalTransaction = transactions.map(function (element) {
return Math.round(element + element * (5 / 100));
});
console.log(FinalTransaction);
OUTPUT:
[210,-105,525,-315,630,735,-262]
Total incoming transactions and outgoing transactions.
We take new arrays
incomingTransaction
to store the value of incoming money.Using forEach loop:
const incomingTransaction = [];
transaction.forEach(function (element, index) {
// Total incomingTransaction and outgoingTransaction money
if (element > 0) incomingTransaction.push(element);
});
console.log(incomingTransaction);
OUTPUT:
[210, 525, 630, 735]
filter() method
The filter()
method creates a shallow copy of a portion of a given array, filter the elements from the given array that pass the condition implemented by the provided function.
Syntax
filter(function (element, index, array) { /* … */ })
callbackFn
A function to execute for each element in the array. It should return a truthy to keep the element in the resulting array, and a falsy value otherwise.
The function is called with the following arguments:
element
The current element is being processed in the array.
index
The index of the current element being processed in the array.
array
The array filter()
was called upon.
By using the filter() method we can do it like this:
const incomingTransaction = [];
const incomingTransaction = transactions.filter((element,index,array) => {
return element > 0;
});
console.log(incomingTransaction1);
OUTPUT:
[210, 525, 630, 735]
Calculate the total amount.
Using forEach loop:
const transactions = [200, -100, 500, -300, 600, 700, -250];
const TotalAmount;
transaction.forEach(function (element, index) {
// Total sum
TotalAmount += element;
});
console.log(TotalAmount);
OUTPUT:
1350
reduce() method
The reduce()
method executes a "reducer" callback function on each element of the array, in order, to pass in the return value from the calculation on the preceding element.
The final result of running the reducer across all elements of the array is a single value.
Syntax
reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }, initialValue)
callbackFn
A function to execute for each element in the array.
Its return value becomes the value of the accumulator
parameter on the next invocation of callbackFn
.
For the last invocation, the return value becomes the return value of reduce()
.
accumulator
The value resulting from the previous call to callbackFn
.
currentValue
The value of the current element.
currentIndex
The index position of currentValue
in the array.
array
The array reduce()
was called upon.
By using reduce() method:
const transactions = [200, -100, 500, -300, 600, 700, -250];
const balance = transactions.reduce( (acc,currentValue) =>
acc += currentValue,0)
console.log(balance);
OUTPUT:
1350
Conclusion:
We can also chain these three or any two methods altogether to get the desired output that we want.
Play around with these on your own and you will understand them more properly.
So these are the three great Arrays methods you can use for Data Transformations.
Thanks for reading I hope now you know the map(), filter() and reduce() methods in Javascript.
Do give your feedback in the comments below! 😀
Follow me for learning more about JavaScript.
#DevsInTechBlogs