Problem
- There is an array with some numbers.
- All numbers are equal except for one.
- Try to find it.
- It’s guaranteed that array contains at least 3 numbers.
Solution 01
function findUniqueNum(arr) {
let sortArr = arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length; i++) {
if (sortArr[i] !== sortArr[i + 1]) {
return sortArr[i];
} else {
return sortArr[sortArr.length - 1];
}
}
}
findUniqueNum([0, 0, 4]); // 4
findUniqueNum([0, 2, 0]); // 2
findUniqueNum([9, 0, 0]); // 9
findUniqueNum([0, 0, 4, 0]); // 4
Solution 02
function findUniqueNum(arr) {
arr = arr.sort((a, b) => a - b);
return arr[0] === arr[1] ? arr.pop() : arr[0];
}
findUniqueNum([0, 0, 4]); // 4
findUniqueNum([0, 2, 0]); // 2
findUniqueNum([9, 0, 0]); // 9
findUniqueNum([0, 0, 4, 0]); // 4
Solution 03
function findUniqueNum(arr) {
return arr.find(i => arr.indexOf(i) === arr.lastIndexOf(i));
}
findUniqueNum([0, 0, 4]); // 4
findUniqueNum([0, 2, 0]); // 2
findUniqueNum([9, 0, 0]); // 9
findUniqueNum([0, 0, 4, 0]); // 4
Solution 04
function findUniqueNum(arr) {
return arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i))[0];
}
findUniqueNum([0, 0, 4]); // 4
findUniqueNum([0, 2, 0]); // 2
findUniqueNum([9, 0, 0]); // 9
findUniqueNum([0, 0, 4, 0]); // 4
Solution 05
function findUniqueNum(arr) {
return +arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
}
findUniqueNum([0, 0, 4]); // 4
findUniqueNum([0, 2, 0]); // 2
findUniqueNum([9, 0, 0]); // 9
findUniqueNum([0, 0, 4, 0]); // 4