- Related Questions & Answers
- 8085 program to find the element that appears once
- Find the element that appears once in an array where every other element appears twice in C++
- Take an array and find the one element that appears an odd number of times in JavaScript
- Return the element that appears for second most number of times in the array JavaScript
- Finding two missing numbers that appears only once and twice respectively in JavaScript
- Get the item that appears the most times in an array JavaScript
- How to find the one integer that appears an odd number of times in a JavaScript array?
- Finding the first unique element in a sorted array in JavaScript
- Finding first unique element in sorted array in JavaScript
- Array elements that appear more than once?
- Checking for majority element in a sorted array in JavaScript
- Nth smallest element in sorted 2-D array in JavaScript
- Finding number that appears for odd times - JavaScript
- Missing Element in Sorted Array in C++
- Find the second most frequent element in array 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

Suppose, we have a sorted array of literals like this −

const arr = [2, 2, 3, 3, 3, 5, 5, 6, 7, 8, 9];

We are required to write a JavaScript function that takes in one such array and returns the first number that appears only once in the array. If there is no such number in the array, we should return false.

For this array, the output should be 6

Following is the code −

const arr = [2, 2, 3, 3, 3, 5, 5, 6, 7, 8, 9]; const firstNonDuplicate = arr => { let appeared = false; for(let i = 0; i < arr.length; i++){ if(appeared){ if(arr[i+1] !== arr[i]){ appeared = false; }; }else{ if(arr[i+1] === arr[i]){ appeared = true; continue; }; return arr[i]; }; }; return false; }; console.log(firstNonDuplicate(arr));

Following is the output in the console −

6

Advertisements