I'm trying to make a function that will calculate the sum of the odds in a N integer.
For example, if N = 5 => 1+3+5 = 9
Here is my attempt :
const n = 4
let arr = []
let i = 0
while (i < n) {
i++
arr.push(i)
}
console.log(arr)
This code return an array with all integers in N, that's ok.
Now I would like to filter the odds, then make the sum of it. I tried different things without success.
Thank you for your time !
const calculateSum = (n) => {
let sum = 0;
// Start from 1 and increment by 2 (1, 3, 5, 7, 9, 11, etc)
for(let i = 1; i <= n; i+=2) {
sum += i;
}
return sum;
}
I'd suggest using Array.reduce() to get the desired result. We generate all integers from 1 to N using Array.from(), then use .reduce() to add any odd numbers to the sum (accumulator) value.
function getSumOfOddNumbers(n) {
return Array.from({length: n}, (v,k) => k + 1).reduce((sum, cur) => (cur % 2) ? sum + cur: sum, 0);
}
for(let n = 1; n < 10; n += 2) {
console.log(`Odd number sum from 1 to ${n}:`, getSumOfOddNumbers(n));
}
.as-console-wrapper { max-height: 100% !important; top: 0; }