Most efficient array shuffler

前端 未结 4 1795
自闭症患者
自闭症患者 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:56

    Let me post my own answer just to encourage you NOT TO use random sort() method as it will produce not so random output.

    As being said, Fisher-Yates shuffle is the most efficient algorithm for that purpose, and it can be easily implemented with the following ES6 code:

    const src = [...'abcdefg'],
    
          shuffle = arr => arr.reduceRight((r,_,__,s) => 
            (r.push(s.splice(0|Math.random()*s.length,1)[0]), r),[])
    
    console.log(JSON.stringify(shuffle(src)))
    .as-console-wrapper {min-height:100%}

提交回复
热议问题