 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Finding the only even or the only odd number in a string of space separated numbers in JavaScript
Problem
We are required to write a JavaScript function that takes in a string that contains numbers separated by spaces.
The string either contains all odd numbers and only one even number or all even numbers and only one odd number. Our function should return that one different number from the string.
Example
Following is the code −
const str = '2 4 7 8 10'; const findDifferent = (str = '') => {    const odds = [];    const evens = [];    const arr = str    .split(' ')    .map(Number);    arr.forEach(num => {       if(num % 2 === 0){          evens.push(num);       }else{          odds.push(num);       };    });    return odds.length === 1 ? odds[0] : evens[0]; }; console.log(findDifferent(str)); Output
Following is the console output −
7
Advertisements
 