I wrote a function that shuffles the elements of an array.
function shuffle(arr) {
var newarr = [];
var oldarr = arr;
for(var i = 0; i < arr.length; i++) {
var index = Math.floor(Math.random() * arr.length);
newarr.push(arr[index]);
arr.splice(index, 1);
}
return newarr;
}
For some reason, the function only returns half of the array elements. If an array of 7 elements is passed to it, it returns 4 elements. Similarly, if an array with 8 elements is returned.
Where did I go wrong?