Filter(),Map(),Reduce() in Javascript.

Filter(),Map(),Reduce() in Javascript.


Filter:

  • Definition: The filter() method creates a shallow copy of a portion of an array, based on a provided function.

  • Example 1:

      const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];
      const result = words.filter((word) => word.length > 6);
      // Output: ["exuberant", "destruction", "present"]
    
  • Example 2:

      const myNums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
      const newNums = myNums.filter((num) => num > 4);
      // Output: [5, 6, 7, 8, 9, 10]
    
  • Common Mistake:

      // Incorrect code
      const newNums = myNums.filter((num) => {
        num > 4;
      });
      // Output: []
      // Correction: Missing return statement
    

Map:

  • Definition: The map() method creates a new array by applying a function to each element of the original array.

  • Example:

      const myNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
      const newNumsMap = myNumbers.map((num) => num + 10);
      // Output: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
    
  • Chaining Map and Filter:

      const chainedResult = myNumbers
        .map((num) => num * 10)
        .map((num) => num + 1)
        .filter((num) => num >= 40);
    

Reduce:

  • Definition: The reduce() method executes a user-supplied "reducer" callback function on each element of an array.

  • Basic Example:

      const array1 = [1, 2, 3, 4];
      const initialValue = 0;
      const sumWithInitial = array1.reduce(
        (accumulator, currentValue) => accumulator + currentValue,
        initialValue,
      );
      // Output: 10
    
  • Reduce with Array of Objects:

      const shoppingCart = [
        { itemName: "js cource", price: 2999 },
        { itemName: "py cource", price: 999 },
        { itemName: "c++ cource", price: 9999 },
        { itemName: "data science cource", price: 12999 },
      ];
    
      const priceToPay = shoppingCart.reduce((acc, item) => acc + item.price, 0);
      // Output: Sum of all prices in the shopping cart