How to use the filter and reduce methods In Javascript
This method provides a simpler answer by using built-in array features. By using the filter technique, a new array is created that only has the odd elements from the original array. The filtered array is then iterated by using the reduce method, which adds each element to the sum.
Example: The function`sumOfOddNumbers` takes an array, filters out odd numbers, and returns their sum using the `filter` and `reduce` methods. The example shows its usage by finding the sum of odd numbers in an array and printing the result.
function sumOfOddNumbers(arr) {
return arr.filter(num => num % 2 !== 0)
.reduce((acc, num) => acc + num, 0);
}
const numbers = [1, 2, 3, 4, 5];
const oddSum = sumOfOddNumbers(numbers);
// Print the result, which is the sum of odd numbers in the array.
console.log("Sum of odd numbers:", oddSum);
Output
Sum of odd numbers: 9
JavaScript Program to Find Sum of Odd Numbers in an Array
In JavaScript, working with arrays is a common task. Often one needs to manipulate the elements within an array, such as finding specific values or calculating their sum.
Below are the approaches to find the sum of all odd numbers within an array:
Table of Content
- 1. Using a loop
- 2. Using the filter and reduce methods
- 3. Using recursion
- 4. Using forEach
- 5. Using the for…of Loop