# Finding the largest non-repeating number in an array in JavaScript

We are required to write a JavaScript function that takes in an array of Integers as the first and the only argument.

The function should then iterate through the array and pick that largest number from the array which only appeared once in the array. After that, return this number and if there is no unique number in the array, we should return -1.

We are also told that the maximum value of any array element will not exceed 100 and will be greater than 0 which mean −

0 < arr[i] < 101

for all i within the array index.

For example −

If the input array is −

const arr = [35, 37, 33, 39, 34, 39, 38, 31];

Then the output should be −

const output = 38;

Since the array entries will always be less than or equal to 100 and greater than 0, we can simply use an array of length 100 to store the frequency of each number from the original array and then traverse from back to pick the unique element.

## Example

The code for this will be −

Live Demo

const arr = [35, 37, 33, 39, 34, 39, 38, 31];
const pickGreatestUnique = (arr = [], bound = 100) => {
const map = Array(bound).fill(0);
for(let i = 0; i < arr.length; i++){
const num = arr[i];
map[num - 1]++;
}
for(let j = bound - 1; j >= 0; j--){
const frequency = map[j];
if(frequency === 1){
return j + 1;
}
}
return -1;
}
console.log(pickGreatestUnique(arr));

## Output

And the output in the console will be −

38

Updated on: 26-Feb-2021

302 Views