I am trying to run an Javascript algorithm to pick an array and reorder its elements randomly.
For this I need to swap array elements positions. Following this page I tried to do this by 2 different ways:
- Temp variable
A = [1,2,3,4,5]
temp = A[2]
A[2] = A[4]
A[4] = temp
console.log(A)
//Output: [1, 2, 5, 4, 3]
- Array Destructuring Assignment:
A = [1,2,3,4,5];
[A[2],A[4]] = [A[4],A[2]]
console.log(A)
//Output: [1, 2, 5, 4, 3]
Both ways worked properly when tried alone.
But implementing in my algorithm, only the first worked
- Temp variable
function reorder(A) {
for (let i = A.length; i > 0; i--) {
randomIndex = Math.floor(Math.random() * i)
temp = A[randomIndex]
A[randomIndex] = A[i - 1]
A[i - 1] = temp
}
}
A = [1, 2, 3, 4, 5]
reorder(A)
console.log(A)
//Output: Random order
- Array Destructuring Assignment:
function reorder(A) {
for (let i = A.length; i > 0; i--) {
randomIndex = Math.floor(Math.random() * i)
[A[randomIndex], A[i-1]] = [A[i-1], A[randomIndex]]
}
}
A = [1,2,3,4,5]
reorder(A)
console.log(A)
//Output: [1,2,3,4,5]
What is the explanation for this behavior?