- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 ]
- Related Articles
- How to sum all elements in a nested array? JavaScript
- Sum all similar elements in one array - JavaScript
- Can all array elements mesh together in JavaScript?
- How to filter an array from all elements of another array – JavaScript?
- Building frequency map of all the elements in an array JavaScript
- JavaScript Checking if all the elements are same in an array
- How to find the sum of all elements of a given array in JavaScript?
- Return an array of all the indices of minimum elements in the array in JavaScript
- How to replace elements in array with elements of another array in JavaScript?
- Accumulating array elements to form new array in JavaScript
- JavaScript array: Find all elements that appear more than n times
- Sum of all the non-repeating elements of an array JavaScript
- How to detect and replace all the array elements in a string using RegExp in JavaScript?
- Looping through and getting frequency of all the elements in an array JavaScript
- Rearranging array elements in JavaScript

Advertisements