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

156
Views
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 answers
Answer question

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 Report

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 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!