Difference between map and filter

Intro

map and filter are array methods in JavaScript used for processing arrays, but they serve different purposes and have distinct functionalities.

Points of Contrast:

  1. Transformation vs. Selection:

    • Map: Transforms each element of the array using a provided function.
    • Filter: Selects elements from the array based on a condition.
    • Output:
    • Map: Returns an array with the same length, containing transformed elements.
    • Filter: Returns an array containing only elements that meet the condition.
    • Usage of Callback Function:
    • Map: Callback function returns a value for each element.
    • Filter: Callback function returns a boolean for each element.

Real-World Usage:

  1. map Usage:
  2. Transforming Data.
  3. Extracting Properties.
  4. Generating UI Components.
  5. filter Usage:
  6. Filtering Data.
  7. Removing Empty Values.
  8. Data Validation.

Code snippet:

// Example array  
const numbers = [1, 2, 3, 4, 5];  
// map example: square each number  

const squaredNumbers = numbers.map(num => num * num);

console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]

// filter example: select even numbers

const evenNumbers = numbers.filter(num => num % 2 === 0);

console.log(evenNumbers); // Output: [2, 4]

In summary, map and filter are essential for processing arrays in JavaScript, with map used for transforming data and filter used for selecting elements based on conditions.