this is a function given an array of numbers to find the one that appears an odd number of times.
what I did is:
- Sort the array
- Check if the array is odd.
- If the array length is 1 then return this value.
- Assign every two values to a new array, and check if it is a number.
- Check if every two values are equals.
- If not equals then the result will be the first element on the new array
function findOdd(A) {
let copA = Array.from(A).sort((a, b) => a - b);
let res = 0;
if (copA.length % 2 === 0) return;
if (copA.length == 1) return res = copA(0);
let newArr = ();
for (let i in copA) {
// if not a integer break
if (!Number.isInteger(copA(i))) {
res = 0;
break;
};
newArr.push(copA(i));
if(newArr.length == 2) {
const (a,b) = newArr;
if (a === b) {
newArr = ();
} else {
res = a;
newArr(0) = b;
break;
}
} else if (newArr.length == 1) {
res = newArr(0);
}
}
return res;
}
// test the code
findOdd((20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5)); // 5
findOdd((1,1,2,-2,5,2,4,4,-1,-2,5)); // -1
findOdd((20,1,1,2,2,3,3,5,5,4,20,4,5)); // 5
findOdd((10)); // 10
findOdd((1,1,1,1,1,1,10,1,1,1,1)); // 10
findOdd((5,4,3,2,1,5,4,3,2,10,10)); // 1
My code works well, but I looking to improve it.