Home > Software engineering >  How to fill missing even numbers in an array of odd numbers concisely?
How to fill missing even numbers in an array of odd numbers concisely?

Time:05-28

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 ].

CodePudding user response:

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

CodePudding user response:

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

  • Related