
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Return Only Odd Numbers from Array in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of integers, arr, as the first and the only argument.
The array either consists of all even numbers and just one odd number or consists of all odd numbers and just one even number. Our function should return this one different element from the array.
For example, if the input to the function is −
Input
const arr = [5, 9, 7, 11, 34, 23, 77];
Output
const output = 34;
Output Explanation
Because the array consists of all odd numbers but 34 which is even.
Example
Following is the code −
const arr = [5, 9, 7, 11, 34, 23, 77]; const findDifferent = (arr = []) => { let { length: len } = arr, i; const evens = []; const odds = []; let k; for (i=0; i<len; i++) { if (arr[i] % 2 == 0) { evens.push(arr[i]); }; if (Math.abs(arr[i] % 2) == 1) { odds.push(arr[i]); }; }; if (evens.len > odds.len) return odds[0]; else return evens[0]; }; console.log(findDifferent(arr));
Output
34
Advertisements