Reducing array elements to all odds in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array. Our function should change the array numbers like this −

  • If the number is odd, leave it changed.
  • If the number is even, subtract 1 from it.

And we should return the new array.

Example

Following is the code −

 Live Demo

const arr = [5, 23, 6, 3, 66, 12, 8];
const reduceToOdd = (arr = []) => {
   const res = [];
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      if(el % 2 === 1){
         res.push(el);
      }else{
         res.push(el - 1);
      };
   };
   return res;
};
console.log(reduceToOdd(arr));

Output

Following is the console output −

[ 5, 23, 5, 3, 65, 11, 7 ]
raja
Published on 20-Apr-2021 07:51:53
Advertisements