- 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

# 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

- Related Articles
- Adding only odd or even numbers JavaScript
- Finding the greatest and smallest number in a space separated string of numbers using JavaScript
- Finding the only unique string in an array using JavaScript
- Returning only odd number from array in JavaScript
- How to transform two or more spaces in a string in only one space? JavaScript
- Check if the String has only unicode digits or space in Java
- State whether the following statements are True or False:(a) The sum of three odd numbers is even.(b) The sum of two odd numbers and one even number is even.(c) The product of three odd numbers is odd.(d) If an even number is divided by 2, the quotient is always odd.(e) All prime numbers are odd.(f) Prime numbers do not have any factors.(g) Sum of two prime numbers is always even.(h) 2 is the only even prime number.(i) All even numbers are composite numbers.(j) The product of two even numbers is always even.
- Write a number array and using for loop add only even numbers in javascript?
- Write a number array and add only odd numbers?
- Repeating only even numbers inside an array in JavaScript
- Checking for Null or Empty or White Space Only String in Java.
- Check if the String contains only unicode letters, digits or space in Java
- Finding the only out of sequence number from an array using JavaScript
- Reverse only the odd length words - JavaScript
- Sum of individual even and odd digits in a string number using JavaScript

Advertisements