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.
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.
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