Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Repeat even number inside the same array - JavaScript
We are required to write a JavaScript function that should repeat the even number inside the same array.
Therefore, for example given the following array ?
const arr = [1, 2, 5, 6, 8];
We should get the output ?
const output = [1, 2, 2, 5, 6, 6, 8, 8];
Example
Following is the code ?
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
This will produce the following output on console ?
[
1, 2, 2, 5,
6, 6, 8, 8
]
How It Works
The function uses array.splice() method to insert duplicate even numbers. We iterate backwards through the array to avoid index shifting issues when inserting elements.
Alternative Method: Using map and flatMap
const arr = [1, 2, 5, 6, 8];
const repeatEvenNumbers = arr => {
return arr.flatMap(num => num % 2 === 0 ? [num, num] : [num]);
};
console.log(repeatEvenNumbers(arr));
[ 1, 2, 2, 5, 6, 6, 8, 8 ]
Conclusion
Both approaches work effectively. The splice method modifies the original array, while flatMap creates a new array. Use flatMap for a functional programming approach or splice when you need to modify the array in place.
Advertisements
