Javascript filter vs reduce
Created By: chatGPT
In JavaScript, both
filter
and reduce
are higher-order functions that operate on arrays, allowing for functional programming patterns. However, they serve different purposes. filter
creates a new array with all elements that pass a test implemented by the provided function, while reduce
applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.To illustrate the difference, here’s how you might use each method to manipulate an array of numbers.Using
In this example, filter
to get even numbers from an array:const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4, 6, 8, 10]
filter
takes a function that checks if a number is even and creates a new array containing only those numbers.Now let’s see how
Here, reduce
can be used to calculate the sum of all numbers in the array:const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 55
reduce
is used to accumulate the sum of all numbers in the numbers
array. The accumulator starts at 0
, and for each number in the array, it adds that number to the accumulator.In summary, use filter
when you want to create a new array with a subset of the elements based on a certain condition and use reduce
when you need to aggregate the values in an array into a single result.