Guest User

Untitled

a guest
Apr 19th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.67 KB | None | 0 0
  1. //***DISCLAIMER: ONLY WORKS FOR POSITIVE NUMBERS***
  2. let arr = [4, 7, 8, 9, 3, 6, 2, 2]
  3.  
  4. arr.forEach((val, i) => {
  5. //Use the absolute value because someone else might have made it negative
  6. val = Math.abs(val)
  7. console.log(arr)
  8. //If the value in the val index is less than 0, we know that the first occurence of the val has changed it to negative. So this is the duplicate one!
  9. if (arr[val] < 0) {
  10. console.log('first duplicate of ' + val + ' at position ' + i)
  11. return
  12. }
  13. //If index is out of bounds, then just assign the negative of the value, else assign negative of whatever value is there in that position already
  14. arr[val] = !arr[val] ? val * -1 : arr[val] * -1
  15. })
Add Comment
Please, Sign In to add comment