Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Map entries() Method
Next article icon

Map() vs Filter() Methods in JavaScript

Last Updated : 22 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

In JavaScript, the map() and filter() methods are powerful array functions that allow you to transform and filter arrays easily. We will discuss the required concepts about each method in this article.

What is map() in JavaScript?

The map() method creates a new array by applying a given function to each element of the original array. It transforms each element according to the logic defined in the callback function without altering the original array.

Syntax:

array.map(function_to_be_applied)
array.map(function (args) {
    // code;
})

Example 1: In this example, we will transform each element by multiplying with 3.

JavaScript
const numbers = [5, 10, 15, 20, 25, 30];

const multipliedNumbers = 
    numbers.map(num => num * 3);
console.log(multipliedNumbers)

Output
[ 15, 30, 45, 60, 75, 90 ]

Example 2: In this example, we will transform all values making them uppercase alphabets.

JavaScript
const fruits = [
    { name: 'apple', color: 'red' },
    { name: 'banana', color: 'yellow' },
    { name: 'kiwi', color: 'green' },
    { name: 'orange', color: 'orange' },
    { name: 'pineapple', color: 'yellow' }
];

const transformedFruits = fruits.map(fruit => ({
    fruitName: fruit.name.toUpperCase(),
    fruitColor: fruit.color.toUpperCase()
}));

console.log(transformedFruits);

Output:

[
  { fruitName: 'APPLE', fruitColor: 'RED' },
  { fruitName: 'BANANA', fruitColor: 'YELLOW' },
  { fruitName: 'KIWI', fruitColor: 'GREEN' },
  { fruitName: 'ORANGE', fruitColor: 'ORANGE' },
  { fruitName: 'PINEAPPLE', fruitColor: 'YELLOW' }
]

What is filter() in JavaScript?

The filter() method creates a new array containing only elements that satisfy a specified condition. It does not change the original array and is useful for selecting specific elements from an array based on certain criteria.

Syntax:

array.filter(function_to_be_applied)
array.filter(function (args) {
    // condition;
}) 

Example 1: In this example, we will filter the values greater than 20.

JavaScript
const numbers = [5, 10, 15, 20, 25, 30];

const numbersGreaterThan20 = 
    numbers.filter(num => num > 20);

console.log(numbersGreaterThan20); 

Output
[ 25, 30 ]

Example 2: In this example, we will filter the fruites having the color yellow.

JavaScript
// Using filter to get fruits which are yellow in color
const fruits = [
    { name: 'apple', color: 'red' },
    { name: 'banana', color: 'yellow' },
    { name: 'kiwi', color: 'green' },
    { name: 'orange', color: 'orange' },
    { name: 'pineapple', color: 'yellow' }
];

const yellowFruits = 
    fruits.filter(fruit => fruit.color === 'yellow');

console.log(yellowFruits);

Output
[
  { name: 'banana', color: 'yellow' },
  { name: 'pineapple', color: 'yellow' }
]

Differences of Map() and Filter() methods

map()

filter()

Creates a new array with the same length as the original array, but with each element transformed by the callback function.

Creates a new array with only the elements that pass the conditions implemented by the callback function.

Used when you want to transform each element in an array

Used when you want to select only certain elements that meet a specific condition.

Returns a new array with the same length as the original array.

Returns a new array with a length that is equal to or less than the original array.

The map() and filter() methods are fundamental tools in JavaScript for working with arrays. While both are used to create new arrays, their purposes are distinct:

  • Use map() when you need to transform or manipulate every element in an array.
  • Use filter() when you want to select specific elements that meet a particular condition.

Next Article
JavaScript Map entries() Method

R

rehantwick
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-array
  • JavaScript-Methods

Similar Reads

    Filter or map nodelists in JavaScript
    When working with HTML elements in JavaScript, you often get a NodeList, which is a collection of elements that match a certain selector. However, NodeLists don't have built-in methods for filtering or mapping as arrays do.These are the following approaches:Table of ContentUsing Array.from() and fil
    2 min read
    JavaScript Map clear() Method
    JavaScript Map.clear() method is used for the removal of all the elements from a map and making it empty. It removes all the [key, value] from the map. No arguments are required to be sent as parameters to the Map.clear() method and it returns an undefined return value.Syntax:mapObj.clear()Parameter
    3 min read
    JavaScript Map clear() Method
    JavaScript Map.clear() method is used for the removal of all the elements from a map and making it empty. It removes all the [key, value] from the map. No arguments are required to be sent as parameters to the Map.clear() method and it returns an undefined return value.Syntax:mapObj.clear()Parameter
    3 min read
    Set vs Map in JavaScript
    In JavaScript, Set and Map are two types of objects that are used for storing data in an ordered manner. Both these data structures are used to store distinct types of data inside the same object. In Maps, the data is stored as a key-value pair whereas in Set data is a single collection of values th
    2 min read
    JavaScript Map entries() Method
    JavaScript Map.entries() method is used for returning an iterator object which contains all the [key, value] pairs of each element of the map. It returns the [key, value] pairs of all the elements of a map in the order of their insertion. The Map.entries() method does not require any argument to be
    4 min read
    JavaScript Map entries() Method
    JavaScript Map.entries() method is used for returning an iterator object which contains all the [key, value] pairs of each element of the map. It returns the [key, value] pairs of all the elements of a map in the order of their insertion. The Map.entries() method does not require any argument to be
    4 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences