I devised a JavaScript method to select items from an array and display the final item. However, I noticed that this process was inadvertently removing items from the original array.
Here is the function:
function oneRemaining(arr) {
tmp = arr;
while (tmp.length > 1) {
tmp.splice(~~(Math.random() * tmp.length), 1);
}
return tmp[0];
}
After executing this function, the initial array should remain unchanged because it was not supposed to be modified. Unfortunately, when I tested it in the console, only one item was left in the array.
What could be causing the input array to be altered?