Question 1

Question

Explain the difference between Array.prototype.filter() and Array.prototype.reduce().

Answer

Array.prototype.filter()

  • Purpose: Creates a new array containing only the elements from the original array that pass a certain test (defined by the provided function).

  • How it works: It iterates through each element in the array, calls the provided function for each element, and includes the element in the new array if the function returns true.

  • Result: A new array with elements that meet the condition.

    const numbers = [1, 2, 3, 4, 5];
    
    const evenNumbers = numbers.filter(number => number % 2 === 0); 
    console.log(evenNumbers); // Output: [2, 4]

Array.prototype.reduce()

  • Purpose: Combines all elements of an array into a single value (accumulator). It's great for performing calculations or aggregating data from the array.

  • How it works: It iterates through each element in the array, accumulating a value based on the current element and the previously accumulated value (the "reducer" function provides this logic).

  • Result: A single value representing the aggregated result of all elements in the array.

    const numbers = [1, 2, 3, 4, 5];
    
    const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
    console.log(sum); // Output: 15

In Essence:

  • filter() creates a new array based on criteria. Think "selection."

  • reduce() combines the elements of an array into a single value. Think "aggregation."

Last updated