Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
Sum odds in integer N - JavaScript

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 !

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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;

}
about 4 years ago · Juan Pablo Isaza Report

0

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; }

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!