
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Fetching odd appearance number in JavaScript
Given an array of integers, we are required to write a function that takes this array and finds the one element that appears an odd number of times.
There will always be only one integer that appears an odd number of times. We will approach this problem by sorting the array. Once sorted, we can iterate over the array to pick the element that appears for odd number of times.
Example
The code for this will be −
const arr = [20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5]; const findOdd = arr => { let count = 0; let last; arr.sort((a, b) => a - b); for (let i = 0; i < arr.length; i++){ if (arr[i] === last) { count++; continue; }; if(count % 2){ return last; }; last = arr[i]; count = 1; }; return last; }; console.log(findOdd(arr));
Output
The output in the console will be −
5
- Related Articles
- Fetching JavaScript keys by their values - JavaScript
- Fetching object keys using recursion in JavaScript
- Returning only odd number from array in JavaScript
- Finding number that appears for odd times - JavaScript
- Splitting number to contain continuous odd or even number using JavaScript
- Appearance and Non-Appearance of Parties
- How to determine if a number is odd or even in JavaScript?
- Removing the odd occurrence of any number/element from an array in JavaScript
- Sum of individual even and odd digits in a string number using JavaScript
- Average of odd numbers till a given odd number?
- Separate odd and even in JavaScript
- Reverse the words in the string that have an odd number of characters in JavaScript
- Fashion and Appearance
- Finding the longest consecutive appearance of a character in another string using JavaScript
- Odd even sort in an array - JavaScript

Advertisements