Programming Tutorials

reduce() and filter() in JavaScript

By: Vimala in Javascript Tutorials on 2023-04-26  

reduce() and filter() are higher-order array functions in JavaScript that allow you to perform operations on arrays in a more concise and readable way.

reduce() method is used to reduce an array to a single value by executing a callback function for each element of the array, taking four arguments: the accumulator, the current value, the current index, and the original array.

Here is an example of reduce() being used to find the sum of all elements in an array:

const numbers = [10, 20, 30, 40];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // Output: 100

In the above code, we initialize the accumulator to 0 and then iterate over each element of the array. In each iteration, we add the currentValue to the accumulator, and finally, we get the total sum of all the elements in the array.

filter() method is used to filter out elements from an array that don't meet a specified condition, creating a new array with only the filtered elements.

Here is an example of filter() being used to filter out all even numbers from an array:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const oddNumbers = numbers.filter((number) => number % 2 !== 0);
console.log(oddNumbers); // Output: [1, 3, 5, 7, 9]

In the above code, we use the filter() method to create a new array oddNumbers that contains only the odd numbers from the original numbers array. The condition for filtering is that the number should not be divisible by 2.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Javascript )

Latest Articles (in Javascript)