Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 1865

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 62k
Author
Asked: November 26, 20242024-11-26T12:07:08+00:00 2024-11-26T12:07:08+00:00

Unlocking the Power of Map, Filter, and Reduce in JavaScript

  • 62k

Map, filter and reduce are commonly used in Frontend development. However, developers are often confused about their behaviour. Each array method map, filter and reduce returns a new array based on the result of the function. In this article, you will also learn the power of the reduce method.

Map

The purpose of the Map() method in JavaScript is to transform each element of an array using a provided callback function and then return a new array containing the transformed elements.

const numbers=[2,3,4,5,6,7];  numbers.map(function(element, index, array){     console.log('element',element, 'index',index,'array', array); }) 
Enter fullscreen mode Exit fullscreen mode

Output

element 2 index 0 array [ 2, 3, 4, 5, 6, 7 ] element 3 index 1 array [ 2, 3, 4, 5, 6, 7 ] element 4 index 2 array [ 2, 3, 4, 5, 6, 7 ] element 5 index 3 array [ 2, 3, 4, 5, 6, 7 ] element 6 index 4 array [ 2, 3, 4, 5, 6, 7 ] element 7 index 5 array [ 2, 3, 4, 5, 6, 7 ] 
Enter fullscreen mode Exit fullscreen mode

Are you afraid of seeing the syntax of the map? Don't worry. I'm here to explain you.

Map takes 3 parameters elements, index and array. However, you need only element to transform into a new array. Keep in mind that the word transformed. For example, Suppose I have an array containing 5 numbers (1 to 5). I want to double each element, but I could also triple them or perform other transformations. Here is an example below.

const numbers=[1,2,3,4,5];  const doubleIt= numbers.map((element)=>element*2); console.log(doubleIt) //[ 2, 4, 6, 8, 10 ] 
Enter fullscreen mode Exit fullscreen mode

Remember the purpose of the array method transform each element of an array and return a new array containing the transformed elements. here numbers transformed in [2,4,6,8,10]. I hope now it is clear.

Apply Map

Now is the time to apply a map example for better understanding. Here is an example below

const students = [     {id:1, name: 'Ahmed', age: 19, email: 'ahmed@gmail.com' },     {id:2, name: 'Rahman', age: 23, email: 'rahman@gmail.com' },     {id:3, name: 'Bablu', age: 22, email: 'bablu@gmail.com' },     {id:4, name: 'Jakir', age: 21, email: 'jakir@gmail.com' },     {id:5, name: 'Mahin', age: 17, email: 'mahin@gmail.com' }, ];  
Enter fullscreen mode Exit fullscreen mode

From student array, you want to display only the ID and email of the student. How can you do that?

const studentIdAndEmail = students.map(student => {     return { id: student.id, email: student.email }; }); console.log(studentIdAndEmail); 
Enter fullscreen mode Exit fullscreen mode

Output:

[     { id: 1, email: 'ahmed@gmail.com' },     { id: 2, email: 'rahman@gmail.com' },     { id: 3, email: 'bablu@gmail.com' },     { id: 4, email: 'jakir@gmail.com' },     { id: 5, email: 'mahin@gmail.com' } ] 
Enter fullscreen mode Exit fullscreen mode

Filter

The Filter() method checks each item in an array based on a condition set by a function. If this condition returns true, the element gets pushed to the output array. If the condition returns false, the element does not get pushed to the output array.

const numbers=[2,3,4,5,6,7];  const filteredNum= numbers.filter((element)=>element>4); console.log(filteredNum);//[ 5, 6, 7 ] 
Enter fullscreen mode Exit fullscreen mode

Remember I mentioned the filter() method which will check each in an array based on a condition. Pay attention to the word =Condition. In the above, you will see a condition applied if the array element is greater than 4 then it will return a new array. As a result, it returns a [5,6,7]

Apply Filter

Now is the time to apply a filter example for better understanding. Here is an example below.

const books = [     { title: 'The Great Gatsby', genre: 'Fiction', publish: 1925, edition: 2004 },     { title: 'To Kill a Mockingbird', genre: 'Fiction', publish: 1960, edition: 2006 },     { title: '1984', genre: 'Science Fiction', publish: 1949, edition: 2003 },     { title: 'The Catcher in the Rye', genre: 'Fiction', publish: 1951, edition: 2001 },     { title: 'Pride and Prejudice', genre: 'Romance', publish: 1813, edition: 2005 },     { title: 'The Hobbit', genre: 'Fantasy', publish: 1937, edition: 2012 },     { title: 'The Da Vinci Code', genre: 'Thriller', publish: 2003, edition: 2018 },     { title: 'Harry Potter and the Philosopher's Stone', genre: 'Fantasy', publish: 1997, edition: 2014 },     { title: 'The Lord of the Rings', genre: 'Fantasy', publish: 1954, edition: 2001 }, ]; 
Enter fullscreen mode Exit fullscreen mode

From the books array you want to display a book whose genre is “Thriller” and that was published after 2000. How can you display it?

const filterBookData= books.filter((book)=>{     return book.genre==='Thriller' && book.publish>=2000 }) console.log(filterBookData)  
Enter fullscreen mode Exit fullscreen mode

Output

 [  {     title: 'The Da Vinci Code',     genre: 'Thriller',     publish: 2003,     edition: 2018   } ] 
Enter fullscreen mode Exit fullscreen mode

Reduce

The reduce() method may seem difficult at first. When you see the tutorials of the reduce method you often come across the same example repeatedly, which is summation. But Reduce is more powerful than simple summation. it combines all elements of an array into a single value by applying a function repeatedly.

Don't worry. Reduce is not that hard the way you think. Suppose you have a piggy bank and a bunch of coins scattered on your table. Each coin has a number written on it representing its value.

Now, you want to find out the total value of all coins you have?
So, you start picking up each coin, one by one, and you keep adding its value to the amount you've already collected in your piggy bank. The amount in your piggy bank keeps growing as you add more coins.

In this story:

  • The piggy bank represents the accumulator, which keeps track of the total value collected so far.
  • Each coin represents the currentValue, the individual value being added to the accumulator.
  • By the end, the total amount in your piggy bank represents the final result returned by the reduce() method.

Based on this story I will give you a example so, that you will more clear about the topic.

const coins = [5, 10, 25, 50, 100];   const totalValue = coins.reduce((accumulator, currentValue) => {      return accumulator + currentValue; }, 0); // 0 is the initial value of the accumulator  console.log("Total value of coins:", totalValue); // Output: Total value of coins: 190  
Enter fullscreen mode Exit fullscreen mode

I have told you reduce() is more powerful than summation. Here is the example below.

const names = [     'Al-Amin',     'Abdul',     'Abu boklor',     'Bijoy ',     'Bisso',     'Emran',     'Fahad',     'Fahim',     'Hamim',     'HM Rahman',     'Hridoy Ahmed',     'Jahid Mia',     'Johir',     'Md Al-Amin',     'Md Rakib',  ];  
Enter fullscreen mode Exit fullscreen mode

From this name array I want to display namesGroup like this

Output:

{   A: [ 'Al-Amin', 'Abdul', 'Abu boklor' ],   B: [ 'Bijoy ', 'Bisso' ],   E: [ 'Emran' ],   F: [ 'Fahad', 'Fahim' ],   H: [ 'Hamim', 'HM Rahman', 'Hridoy Ahmed' ],   J: [ 'Jahid Mia', 'Johir' ],   M: [ 'Md Al-Amin', 'Md Rakib' ] } 
Enter fullscreen mode Exit fullscreen mode

Here is code below:

const namesGroup= names.reduce((acc, curr)=>{     const firstLetter= curr[0].toUpperCase();     if(firstLetter in acc){         acc[firstLetter].push(curr)     }     else{         acc[firstLetter] = [curr];     }     return acc; }, {}) console.log(namesGroup) 
Enter fullscreen mode Exit fullscreen mode

Summary

“JavaScript's array methods map, filter, and reduce are powerful tools for manipulating arrays efficiently.

  • map() transforms each element of an array according to a given function, returning a new array of the transformed elements.
  • filter() selects elements from an array based on a specified condition, returning a new array containing only those elements.
  • reduce() applies a function to each element of an array, accumulating a single value.

These methods can greatly simplify array manipulation tasks, leading to cleaner and more expressive code. Understanding how and when to use them can significantly improve the efficiency and readability of JavaScript code.”

frontendjavascriptwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.