Advertisement
CLooker

find number that appears only once

Nov 14th, 2018
436
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // array has numbers that appear twice, but not necessarily in order
  2. // except one number will not appear twice
  3. const nums = [0, 0, 1, 1, 2, 2, 3, 4, 4, 5, 5];
  4.  
  5. // faster
  6. const getSingleNum = nums => {
  7.   let pairs = {};
  8.  
  9.   nums.forEach(num =>
  10.     pairs[num]
  11.       ? (delete pairs[num])
  12.       : (pairs[num] = true));    
  13.  
  14.   return Object.keys(pairs)[0];
  15. }
  16.  
  17. // slower
  18. const getSingleNumOther = nums =>
  19.   nums.find((num, i) =>
  20.     !nums.some((otherNum, j) =>
  21.       i !== j && num === otherNum
  22.     )
  23.   );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement