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

159
Vistas
How to fill missing even numbers in an array of odd numbers concisely?

So, I've the following arrays of odd numbers:

const oddNums = [1, 3, 5, 7, 9];

And I want to fill it with the missing even numbers to obtain the result below:

[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

I've done it like this and it works fine, but can it be done in a more concise manner, maybe using array methods?

const oddNums = [1, 3, 5, 7, 9];
const nums = [];
for (let i=0; i<oddNums.length; i++) {
  nums.push(oddNums[i]);
  nums.push(oddNums[i] + 1);
}
console.log(nums);

Note: The odd numbers would always be in sequence but might not begin with 1, for ex: [11, 13, 15] is a valid array. And the output for [11, 13, 15] should be [ 11, 12, 13, 14, 15, 16 ].

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The only information you need is the first (odd) number and the size of the input:

const oddNums = [1, 3, 5, 7, 9];

const result = Array.from({length: oddNums.length*2}, (_, i) => i + oddNums[0]);

console.log(result);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Using Array.prototype.flatMap:

const 
  oddNums = [1, 3, 5, 7, 9],
  nums = oddNums.flatMap(n => [n, n + 1]);

console.log(nums);

Using Array.prototype.reduce and Array.prototype.concat:

const 
  oddNums = [1, 3, 5, 7, 9],
  nums = oddNums.reduce((r, n) => r.concat(n, n + 1), []);

console.log(nums);

Using Array.prototype.reduce and Array.prototype.push:

const 
  oddNums = [1, 3, 5, 7, 9],
  nums = oddNums.reduce((r, n) => (r.push(n, n + 1), r), []);

console.log(nums);

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