When to use map ,filter and reduce?
Apoorv Sharma
Posted on March 10, 2023
Map, filter, and reduce are one of the most common and widely used array methods in JavaScript. These methods have tons of applications while creating a real-world application in react or JavaScript.
User data is generally stored in JSON format and to do operation over it map , filter and reduce plays a crucial role.
In general, though, map, filter, and reduce are powerful and versatile methods that can help you write more concise and expressive code when working with arrays in JavaScript.
Under what conditions map in generally used ?
Use map when you want to create a new array that is a transformed version of the original array.Transform in a sense that if we want to modify each and every element of array for example doubling it or turning each element into its cube etc.
Map takes a callback function that is called once for each element in the array, and returns a new array containing the result of calling the callback function on each element.
Map is used when we need to change or modify each and every element of an array and get the output in array form.
Lets understand this with the help of example-
In the below code ๐, we are transforming each element of array into a doubled value.
const numbers = [1, 2, 3, 4];
const doubledNumbers = numbers.map(num => num * 2);
console.log(doubledNumbers); // [2, 4, 6, 8]
Explanation -
if you have an array of numbers and you need to double each element and create a new array with the doubled values, you can use the map() function. The map() function applies a function to each element of an array and returns a new array with the results.
Under what conditions filter is generally used?
As the name suggests, the filter is used for filtering the array.
The filter() method in JavaScript is used to create a new array with all the elements that pass the condition specified by a callback function.
The filter() method does not modify the original array and returns a new array that contains only the elements that satisfy the condition.
Lets understand it with the help of an example ๐,
how to use filter() to select only the even numbers in an array:
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4, 6]
Explanation -
In this example, the filter() method is used to select only the elements in the numbers array that are even. The resulting array contains only the even numbers in the original array.
Under what circumstances do we have to use both map and filter together?
There are 2 conditions under which we might have to use map and filter together :-
1. To filter elements first and then transform them
Lets understand it with the help of an example ๐,
Suppose you have an array of numbers and you want to filter out the odd numbers and return a new array with the even numbers multiplied by 2.
const numbers = [1, 2, 3, 4, 5, 6];
const evenDoubledNumbers = numbers
.filter(num => num % 2 === 0)
.map(num => num * 2);
console.log(evenDoubledNumbers); // [4, 8, 12]
Explanation -
In this example, the filter() function is used to select only the even numbers from the array, and then the map() function is used to create a new array with the even numbers multiplied by 2(we first filtered and then transformed each element). The resulting array contains only the even numbers from the original array, with each even number multiplied by 2.
2. To first filter out elements and extract a part of it
This condition is mostly applicable when we have array of objects.
Lets understand it with the help of an example ๐,
Suppose you have an array of objects representing books, and you want to filter the books that were published in the last five years and return only their titles.
const books = [
{ title: 'The Alchemist', author: 'Paulo Coelho', year: 1988 },
{ title: 'The Power of Now', author: 'Eckhart Tolle', year: 1997 },
{ title: 'The 5 AM Club', author: 'Robin Sharma', year: 2018 },
{ title: 'Atomic Habits', author: 'James Clear', year: 2018 },
{ title: 'The Lean Startup', author: 'Eric Ries', year: 2011 }
];
const recentBookTitles = books
.filter(book => book.year >= (new Date().getFullYear() - 5))
.map(book => book.title);
console.log(recentBookTitles); // ['The 5 AM Club', 'Atomic Habits']
Explanation -
In this example, the filter() function is used to select only the books published in the last five years, and then the map() function is used to extract the titles of those books(we first filtered and then extracted part of filtered elements). The resulting array contains only the titles of the books published in the last five years.
Under what conditions reduce in generally used ?
Use reduce when you want to create a single value from an array by applying a callback function to each element in the array, and accumulating the result.
Reduce() takes a callback function and an initial value, and returns the accumulated result after calling the callback function on each element in the array.
1.Reduce the elements of array into single value
This is the major purpose of reduce function. We can reduce the values of array into single value by accumulating them. We can accumulate array elements into their sum or average or max element in array.
Lets understand it with the help of an example ๐,
You can use the reduce() method to sum up all the numbers in an array.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15
Explanation -
In this example, the reduce() method is used to sum up all the numbers in the numbers array. The accumulator function adds the current number to the accumulator, which starts with an initial value of 0.
2.Grouping the elements of array into single array/object
Another application of reduce function is grouping the elements of array into single object or array based upon certain criteria.
Lets understand it with the help of an example ,
In the below example ๐, we are grouping the array elements based upon their frequency.
const fruits = ['apple', 'banana', 'orange', 'apple', 'banana', 'apple'];
const frequency = fruits.reduce((acc, fruit) => {
if (!acc[fruit]) {
acc[fruit] = 0;
}
acc[fruit]++;
return acc;
}, {});
console.log(frequency);
// { apple: 3, banana: 2, orange: 1 }
Explanation -
In this example, the reduce() method is used to count the frequency of each fruit in the fruits array. The accumulator function creates a new property for each fruit in the accumulator object and adds 1 to the value for each occurrence of the fruit.
PS:-In order to get the answer in an array only we can use map and filter but reduce can return answer in array as well as in object.
Conclusion
So finally we are at the end of our article. These are just few use use cases of map, filter and reduce. Next time when you encounter a problem statement that makes use of map , filter and reduce, try to analyse why did we use a specific method in this problem. Thank you !
Posted on March 10, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 6, 2024