Repeating Only Even Numbers Inside an Array in JavaScript



We are required to write a JavaScript function that should repeat the even number inside the same array.

For example, given the following array −

const arr = [1, 2, 5, 6, 8];

Output

We should get the output −

const output = [1, 2, 2, 5, 6, 6, 8, 8];

Therefore, let’s write the code for this function −

Example

The code for this will be −

const arr = [1, 2, 5, 6, 8];
const repeatEvenNumbers = arr => {
   let end = arr.length -1;
   for(let i = end; i > 0; i--){
      if(arr[i] % 2 === 0){
         arr.splice(i, 0, arr[i]);
      };
   };
   return arr;
};
console.log(repeatEvenNumbers(arr));

Output

The output in the console will be −

[
   1, 2, 2, 5,
   6, 6, 8, 8
]
Updated on: 2020-10-22T13:27:19+05:30

164 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements