Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //***DISCLAIMER: ONLY WORKS FOR POSITIVE NUMBERS***
- let arr = [4, 7, 8, 9, 3, 6, 2, 2]
- arr.forEach((val, i) => {
- //Use the absolute value because someone else might have made it negative
- val = Math.abs(val)
- console.log(arr)
- //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!
- if (arr[val] < 0) {
- console.log('first duplicate of ' + val + ' at position ' + i)
- return
- }
- //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
- arr[val] = !arr[val] ? val * -1 : arr[val] * -1
- })
Add Comment
Please, Sign In to add comment