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 === 1 identifies odd numbers
  • num % 2 === 0 identifies 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.

Updated on: 2026-03-15T23:19:00+05:30

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements