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
Reducing array elements to all odds in JavaScript
We need to write a JavaScript function that transforms an array by converting all numbers to odd values. The transformation rules are:
- If the number is odd, leave it unchanged.
- If the number is even, subtract 1 from it to make it odd.
This ensures all elements in the resulting array are odd numbers.
Example
Here's how to implement this transformation:
const arr = [5, 23, 6, 3, 66, 12, 8];
const reduceToOdd = (arr = []) => {
const res = [];
for(let i = 0; i
[ 5, 23, 5, 3, 65, 11, 7 ]
Using Array.map() Method
We can achieve the same result more concisely using the map() method:
const arr = [5, 23, 6, 3, 66, 12, 8];
const reduceToOdd = (arr = []) => {
return arr.map(num => num % 2 === 0 ? num - 1 : num);
};
console.log(reduceToOdd(arr));
[ 5, 23, 5, 3, 65, 11, 7 ]
How It Works
The function checks each number using the modulo operator (%):
-
num % 2 === 1identifies odd numbers -
num % 2 === 0identifies even numbers - Even numbers are decremented by 1 to become odd
Comparison
| Method | Readability | Performance | Code Length |
|---|---|---|---|
| For loop | Clear logic flow | Fast | Longer |
| Array.map() | More concise | Slightly slower | Shorter |
Conclusion
Both approaches effectively convert arrays to contain only odd numbers. Use the for loop for better performance or map() for more functional programming style.
Advertisements
