# sort - trier tableau javascript

## Comment puis-je mélanger un tableau? (2)

Dupliquer possible:
Comment randomiser un tableau javascript?

Je veux mélanger un tableau d'éléments en JavaScript comme ceux-ci:

``````[0, 3, 3] -> [3, 0, 3]
[9, 3, 6, 0, 6] -> [0, 3, 6, 9, 6]
[3, 3, 6, 0, 6] -> [0, 3, 6, 3, 6]
``````

``````/**
* Shuffles array in place.
* @param {Array} a items An array containing the items.
*/
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
``````

## ES2015 (ES6) version

``````/**
* Shuffles array in place. ES6 version
* @param {Array} a items An array containing the items.
*/
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
``````

Notez cependant que l'échange de variables avec affectation déstructurante entraîne une perte de performance significative, à partir d'octobre 2017.

## Utilisation

``````var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);
``````

Vous pouvez utiliser le Shuffle Fisher-Yates (code adapté de ce site ):

``````function shuffle(array) {
let counter = array.length;

// While there are elements in the array
while (counter > 0) {
// Pick a random index
let index = Math.floor(Math.random() * counter);

// Decrease counter by 1
counter--;

// And swap the last element with it
let temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}

return array;
}
``````