Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

157
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda