# Question regarding shuffling array

**URL:** <https://forum.kirupa.com/t/question-regarding-shuffling-array/636776>\
**Category:** programming\
**Created:** [June 17, 2017, 1:47pm UTC](https://forum.kirupa.com/t/question-regarding-shuffling-array/636776 "2017-06-17T13:47:17Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![iamgeorgegreene](https://avatars.discourse-cdn.com/v4/letter/i/aeb1de/32.png) [@iamgeorgegreene](https://forum.kirupa.com/u/iamgeorgegreene)\
**Post date:** [June 17, 2017, 1:47pm UTC](https://forum.kirupa.com/t/question-regarding-shuffling-array/636776/1 "2017-06-17T13:47:17Z")

</div>

## Can anyone explain why and how swapping is done on these two lines?

```
/*
input[randomIndex] = input[i]; 
        input[i] = itemAtIndex;
*/

Array.prototype.shuffle = function() {
    var input = this;
     
    for (var i = input.length-1; i >=0; i--) {
     
        var randomIndex = Math.floor(Math.random()*(i+1)); 
        var itemAtIndex = input[randomIndex]; 
         
        input[randomIndex] = input[i]; 
        input[i] = itemAtIndex;
    }
    return input;
}
 
var tempArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
tempArray.shuffle();
 
// and the result is...
alert(tempArray);
```

---

<div class="post-metadata">

**Author:** ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)\
**Post date:** [June 17, 2017, 5:16pm UTC](https://forum.kirupa.com/t/question-regarding-shuffling-array/636776/2 "2017-06-17T17:16:01Z")

</div>

This diagram [from the tutorial](https://www.kirupa.com/html5/shuffling_array_js.htm) is the key:

[![](https://www.kirupa.com/flash/images/random_selected_number.png) ](https://www.kirupa.com/flash/images/random_selected_number.png)

We need a temporary location to store the value we are swapping. The “4” is stored at `itemAtIndex`. The rest should be straightforward. Once the value is stored, those two lines swap the values between both array locations.

Does that help? 🙂

---

<div class="post-metadata">

**Author:** ![iamgeorgegreene](https://avatars.discourse-cdn.com/v4/letter/i/aeb1de/32.png) [@iamgeorgegreene](https://forum.kirupa.com/u/iamgeorgegreene)\
**Post date:** [June 21, 2017, 1:18pm UTC](https://forum.kirupa.com/t/question-regarding-shuffling-array/636776/3 "2017-06-21T13:18:09Z")

</div>

It does thanks! 😀
