Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda