I am creating a function that returns the unique integer from an array parameter. I have written a function that works, but it is too slow. The function passes all the logical tests but times out.
The functions accepts an argument such as this:
[9,2,1,2,1,6,1,1,6,2,8,1,8]
My Function:
function findUnique(numbers) {
let unqNumber, matchCount,i,y;
let len = numbers.length;
for (i = 0; i < len; i++ ) {
matchCount = 0;
for (y = 0; y < len; y++ ) {
if (numbers[i] == numbers[y]) {
matchCount++;
}
}
if (matchCount == 1) {
unqNumber = numbers[i]
}
}
return unqNumber;
}
It compares each index to all other indexes and counts the occurrences. The index with only 1 occurrence is the unique number.
There is ALWAYS only ONE unique number in the array being passed in.
I know for loops are inefficient but I don't know another way to write it. Could I use filter() or map() to accomplish this faster and more efficiently?