Find the unique number

Lee·2022년 7월 17일

Algorithm

목록 보기
50/92
post-thumbnail

❓ Find the unique number

Q. There is an array with some numbers. All numbers are equal except for one. Try to find it!

findUniq([ 1, 1, 1, 2, 1, 1 ]) === 2
findUniq([ 0, 0, 0.55, 0, 0 ]) === 0.55
It’s guaranteed that array contains at least 3 numbers.

The tests contain some very huge arrays, so think about performance.

This is the first kata in series:

Find the unique number (this kata)
Find the unique string
Find The Unique

✔ Solution

//#my solution
function findUniq(array) {
  // do magic
  return array.find((item) => array.indexOf(item) === array.lastIndexOf(item))
}


//other solution
function findUniq(arr) {
  arr.sort((a,b)=>a-b);
  return arr[0]==arr[1]?arr.pop():arr[0]
}
profile
Lee

0개의 댓글