Transforming Arrays

  • This lesson explains how to transform arrays using modern JavaScript methods.
  • Introduction to Array Transformation

    In real-world JavaScript applications, we rarely use arrays only for storing data.
    Most of the time, we need to:

    • Modify array values

    • Extract specific data

    • Calculate totals or summaries

    • Convert one array into another

    These operations are called array transformations.

    JavaScript provides powerful built-in methods to transform arrays efficiently:

    1. map()

    2. filter()

    3. reduce()

    These methods:

    • Do not change the original array

    • Return a new value or array

    • Are widely used in modern JavaScript and frameworks

    Why Use map(), filter(), reduce() ?

    Without these methods:

    • Code becomes long

    • Manual loops are required

    • Logic becomes repetitive

    With these methods:

    • Code becomes clean and readable

    • Logic is easier to understand

    • Functional programming style is achieved

      map()

      What is map() ?

      The map() method is used to transform each element of an array and return a new array of the same length.

      In simple words:

      map() changes every element of an array.

      Syntax of map()

      array.map(function(currentValue, index, array) {

        return newValue;

      });

      • currentValue → current element

      • index → position (optional)

      • array → original array (optional)

    map Method in Arrays

    Creates a new array by applying a transformation to each element.

    // Multiply each number by 2 using map
    
    let numbers = [1, 2, 3, 4, 5];
    
    let doubled = numbers.map(function(num) {
      return num * 2;
    });
    
    console.log(doubled); // [2, 4, 6, 8, 10]
    • Original array remains unchanged.

      How map() Works Step-by-Step

      Array: [1, 2, 3]

      • Takes 1 → returns 2

      • Takes 2 → returns 4

      • Takes 3 → returns 6

      New array is created.

      When to Use map()

      • When every element needs modification

      • When output array size is same as input

      • When transforming data structure

      filter()

      What is filter() ?

      The filter() method is used to select elements that satisfy a condition and return a new array.

      In simple words:

      filter() removes unwanted elements.

      Syntax of filter()

      array.filter(function(currentValue, index, array) {

        return condition;

      });

      • Returns true → element included

      • Returns false → element excluded

    filter Method in Arrays

    Creates a new array by keeping only elements that match a condition.

    // Filter even numbers
    
    let numbers = [1, 2, 3, 4, 5, 6];
    
    let evenNumbers = numbers.filter(function(num) {
      return num % 2 === 0;
    });
    
    console.log(evenNumbers); // [2, 4, 6]
    • How filter() Works Step-by-Step

      Array: [1, 2, 3]

      • 1 → false

      • 2 → true 

      • 3 → false

        When to Use filter()

        • When selection is required

        • When output array length may change

        • When removing unwanted data

        reduce()

        What is reduce() ?

        The reduce() method is used to combine all array elements into a single value.

        That value can be:

        • Number

        • String

        • Object

        • Array

        In simple words:

        reduce() reduces an array to one result.

        Syntax of reduce()

        array.reduce(function(accumulator, currentValue, index, array) {

          return updatedAccumulator;

        }, initialValue);

        Key Terms in reduce()

        • Accumulator → stores the final result

        • Current Value → current element

        • Initial Value → starting value of accumulator

      reduce Method in Arrays

      Combines all elements of an array into a single value.

      // Sum of numbers using reduce
      
      let numbers = [10, 20, 30, 40];
      
      let sum = numbers.reduce(function(total, num) {
        return total + num;
      }, 0);
      
      console.log(sum); // 100
      • map vs filter vs reduce
        MethodPurposeOutput
        map()Transform elementsNew array (same length)
        filter()Select elementsNew array (filtered)
        reduce()Combine elementsSingle value

        Common Mistakes

        • Expecting map() to filter values

        • Forgetting return statement

        • Not providing initial value in reduce()

        • Modifying original array unintentionally

        Best Practices

        • Use map() for transformation

        • Use filter() for selection

        • Use reduce() for calculations

        • Keep callback functions simple

        • Prefer readability over complexity

        Analogy

        • map() → Convert prices from USD to INR

        • filter() → Select students who passed

        • reduce() → Calculate total bill amount