- Related Questions & Answers
- How to find the one integer that appears an odd number of times in a JavaScript array?
- Finding number that appears for odd times - JavaScript
- Get the item that appears the most times in an array JavaScript
- Return the element that appears for second most number of times in the array JavaScript
- Find the element that appears once in an array where every other element appears twice in C++
- Find the element that appears once in sorted array - JavaScript
- Removing the odd occurrence of any number/element from an array in JavaScript
- Find the number of times a value of an object property occurs in an array with JavaScript?
- Number of times a string appears in another JavaScript
- Counting how many times an item appears in a multidimensional array in JavaScript
- Take an array of integers and create an array of all the possible permutations in JavaScript
- Java Program to Find the Number Occurring Odd Number of Times
- 8085 program to find the element that appears once
- C/C++ Program to Find the Number Occurring Odd Number of Times?
- Reverse the words in the string that have an odd number of characters in JavaScript

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

Following is the code −

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));

This will produce the following output −

5

Advertisements