2

Which is the more efficient way to shuffle an array in JavaScript?

Algorithm 1:

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;
}

Algorithm 2:

function shuffle(a) {    
  return a.sort(() => 0.5 - Math.random());
}

Please explain your answer!

Zali
  • 21
  • 1

0 Answers0