# Returning only odd number 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 −

Live Demo

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

Updated on: 22-Apr-2021

474 Views