Home Ask Login Register

Developers Planet

Your answer is one click away!

Julio M. February 2016

I need to disorder an array

Hello I need disorder an array. I tryed something like this:

var letras = ['a', 'e', 'i', 'o', 'u'];

function disorder(p){

    pos = Math.random()*p.length;

But it doesnt work, and I am not sure that was memory efficient because of the deletes.


Nina Scholz February 2016

You need an integer as index.

pos = Math.random() * p.length | 0;

The bitwise or cast the value to integer.

function disorder(p) {
    var i, pos, temp;
    for (i = 0; i < 100; i++) {
        pos = Math.random() * p.length | 0;
        temp = p[pos];
        p.splice(pos, 1);

var letras = ['a', 'e', 'i', 'o', 'u'], p = []

document.write('<pre>' + JSON.stringify(letras, 0, 4) + '</pre>');

Matthew Herbst February 2016

How about just doing a random sort?

var letras = ['a', 'e', 'i', 'o', 'u'];

function disorder(arr, entropy){
  var disorderedArr = arr.sort(function(a, b) {
    return Math.floor(Math.random() * entropy); 

  return disorderedArr;

var disorderedLetras = disorder(letras, 10);
document.write('<pre>' + JSON.stringify(disorderedLetras, 0, 4) + '</pre>');

While probably not statistically vigorous, this will do what you want and gives you some control over how random things actually will be.

Post Status

Asked in February 2016
Viewed 1,852 times
Voted 7
Answered 2 times


Leave an answer

Quote of the day: live life