- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reducing array elements to all odds in JavaScript
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 −
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 ]
Advertisements