Most efficient array shuffler

前端 未结 4 1804
自闭症患者
自闭症患者 2020-12-07 02:42

How can I shuffle an array\'s values in the most efficient manner possible?

Each element is just a string containing HTML.

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-07 02:45

    You have a few choices.

    First, you could use the stupidely naïve sorter...

    arr = arr.sort(function() {
        return Math.random() - .5
    });
    

    jsFiddle.

    This is quick and dirty but often considered bad practice.

    Further Reading.

    The best way to randomly sort an Array is with the Fisher-Yates shuffle.

    var newArr = [];
    
    while (arr.length) {
    
       var randomIndex = Math.floor(Math.random() * arr.length),
           element = arr.splice(randomIndex, 1)
    
       newArr.push(element[0]);       
    
    }
    

    JSBin.

提交回复
热议问题