Advertisement
fueanta

Array items appeared only once in JS

May 26th, 2019
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Write a function which will take an array as a parameter and will return only the numbers that are repeated once.
  2. // Eg: sample array [1, 2, 2, -4, 3, 1, -3, 4, 4, 1, 5, -4],
  3. // output: -3, 3, 5
  4.  
  5. const array = [1, 2, 2, -4, 3, 1, -3, 4, 4, 1, 5, -4]
  6.  
  7. const max = Math.max(...array)
  8.  
  9. const min = Math.min(...array)
  10.  
  11. const positive_counts = []
  12.  
  13. const negative_counts = []
  14.  
  15. const answers = []
  16.  
  17. for (let i = 0; i <= max; i++) {
  18.     positive_counts[i] = 0
  19. }
  20.  
  21. for (let i = 0; i <= (-1 * min); i++) {
  22.     negative_counts[i] = 0
  23. }
  24.  
  25. for (let i = 0; i < array.length; i++) {
  26.     if (array[i] >= 0) {
  27.         positive_counts[array[i]]++
  28.     } else {
  29.         negative_counts[(-1 * array[i])]++
  30.     }
  31. }
  32.  
  33. for (let i = 0; i < negative_counts.length; i++) {
  34.     if (negative_counts[i] == 1) {
  35.         answers.push((-1 * i))
  36.     }
  37. }
  38.  
  39. for (let i = 0; i < positive_counts.length; i++) {
  40.     if (positive_counts[i] == 1) {
  41.         answers.push(i)
  42.     }
  43. }
  44.  
  45. console.log(answers)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement