Introduction
When it comes to developing in JavaScript, knowing higher order functions is like having a magic wand. The three most powerful ones are Map, Filter, and Reduce, which give programmers the most flexibility and efficiency when working with arrays. These functions are more than just iteration; they allow for the elegant and precise alteration, selection, and consolidation of data. Come along on an exploration of the complex inner workings of Map, Filter, and Reduce as we reveal their transformational powers and reveal their secrets.
1.Map Function:
Transformation of Arrays Meticulously
One of the most important JavaScript methods for manipulating arrays is the map() function. It applies a given function to each element iteratively, coordinating the creation of a new array.
for each loop and map() are almost same. But, the difference is map() creates new array and for each loop doesn't create.
examples:
const arr = [5, 1, 3, 2, 6];
// Example 1: Doubling the Array Elements
function double(x) {
return x * 2;
}
const doubleArr = arr.map(double);
console.log(doubleArr); //o/p: [10, 2, 6, 4, 12]
//Example 2: Tripling the Array Elements
function triple(x) {
return x * 3;
}
const tripleArr = arr.map(triple);
console.log(tripleArr); // o/p:[15, 3, 9, 6, 18]
//Example 3: Converting array elements to binary
const arr = [5, 1, 3, 2, 6];
// Transformation logic:
function binary(x) {
return x.toString(2);
}
const binaryArr = arr.map(binary);
// The above code can be rewritten as :
const binaryArr = arr.map(function binary(x) {
return x.toString(2);
}
//Here,to convert number into string or number array into binary array, we use .toString() method with a radix parameter that must be ranging between 2 and 36.
// OR -> Arrow function
const binaryArr = arr.map((x) => x.toString(2));
// o/p: ["101", "1", "11", "10", "110"]
In simple terms, the map function maps every value and modifies it according to the specified criteria.
2.Filter function:
Carefully Picking Array Elements
The filter() method makes array filtering easy by creating a new array with elements that satisfy certain requirements.Only values that evaluate to true are stored in an array created by the filter function.
const array = [5, 1, 3, 2, 6];
// filtering odd values
function isOdd(x) {
return x % 2;
}
const oddArr = array.filter(isOdd); // o/p:[5,1,3]
// Other way of writing the above code using arrow function:
const oddArr = arr.filter((x) => x % 2);//o/p: [5,1,3]
//Now,filtering even values
const evenArr = arr.filter((x) => x % 2 === 0);
console.log(evenArr);//o/p: [2,6]
3.Reduce Function:
Combining Arrays to Get a Single value
The reduce() method is a fundamental tool that combines array values into a single output and provides a great deal of processing flexibility. It iterates over each element of array.
const array = [5, 1, 3, 2, 6];
// Calculate sum of elements of array - by 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)); // o/p:17
// now, by reduce function way
const output= arr.reduce(function (acc, curr) {
acc = acc + curr;
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.
//for iteration, value needed to be passed in accumulator is 0(i.e it will start iteration from 0th index)
//If value is not passed, then index will start from 1.
console.log(output); //o/p: 17
There are 2 parameters in reduce function :
current(curr):
current represent the current value of array. In the above case, curr refers to arr[i].
accumulator(acc):
It accumulates the callback return value or result. acc is just like a label. In the above case, acc refers to sum.
// Another example // find max inside array: Non functional programming way: const array = [5, 1, 3, 2, 6]; function findMax(arr) { let max = 0; for(let i = 0; i < arr.length; i++ { if (arr[i] > max) { max = arr[i] } } return max; } console.log(findMax(array)); //o/p: 6 // using reduce const output = arr.reduce((acc, current) => { if (current > acc ) { acc = current; } return acc; }, 0); console.log(output); // o/p:6 // acc is just a label which represent the accumulated value till now, // so we can also label it as max in this case const output = arr.reduce((max, current) => { if (current > max) { max= current; } return max; }, 0); console.log(output); //o/p: 6
Tricky Map question for Practice:
Acquiring Expertise in Advanced Approaches
The map function opens up complex functionalities and crosses traditional barriers to allow for complex data transformations.
const users = [
{ firstName: "Alok", lastName: "Raj", age: 23 },
{ firstName: "Ashish", lastName: "Kumar", age: 29 },
{ firstName: "Ankit", lastName: "Roy", age: 29 },
{ firstName: "Pranav", lastName: "Mukherjee", age: 50 },
];
// Get array of full name : ["Alok Raj", "Ashish Kumar", ...]
const fullNameArr = users.map((user) => user.firstName + " " + user.lastName);
console.log(fullNameArr); // o/p: ["Alok Raj", "Ashish Kumar", ...]
-------------------------------------------------------------------------------
// Get the count/report of how many unique people with unique age are there
// like: {29 : 2, 75 : 1, 50 : 1}
// We should use reduce, why? we want to deduce some information from the array. Basically we want to get a single object as output
const report = users.reduce((acc, curr) => {
if(acc[curr.age]) {
acc[curr.age] = ++ acc[curr.age] ;
} else {
acc[curr.age] = 1;
}
return acc; //to every time return update object
}, {})
console.log(report) // o/p: {29 : 2, 75 : 1, 50 : 1}
Function Chaining:
Smooth Integration for Increased Productivity
JavaScript's function chaining feature enables programmers to create solutions that promote readability and efficiency in code.
Example:
// First name of all people whose age is less than 30
const users = [
{ firstName: 'siddhesh', lastName: 'Raj', age: 23 },
{ firstName: 'joy', lastName: 'Kumar', age: 29 },
{ firstName: 'pari', lastName: 'Roy', age: 29 },
{ firstName: 'Pankaj', lastName: 'Mukherjee', age: 50 },
];
// Function chaining
const output = users
.filter((user) => user.age < 30)
.map((user) => user.firstName);
console.log(output); //o/p: ["siddhesh", "joy", "pari"]
// Now,Implementing the same logic using reduce() function.
const outputReduce = users.reduce((acc, curr) => {
if (curr.age < 30) {
acc.push(curr.firstName);
}
return acc;
}, []);
console.log(outputReduce); //o/p: ["siddhesh", "joy", "pari"]
conclusion:
JavaScript's Map, Filter, and Reduce methods provide effective array manipulation. Reduce shrinks values, Filter chooses based on criteria, and Map transforms elements. Function chaining, when used with these functions, simplifies the code and improves its readability and scalability. Gaining proficiency with these tools enables developers to take on challenging projects with ease and guarantees beautiful and effective JavaScript programming.