0
const cardArray = [ {a:1},{a:2},{a:3},{a:5} ]
     //first console.log
     console.log(cardArray);
  cardArray.sort((a,b) => 0.5 - Math.random());
    //second console.log
     console.log(cardArray); 

Why I'm getting the same result in the first and second console.log() ?

Note: I get the expected result when I use an array with number elements. example : const cardArray = [1,2,3,5]

  1. first cosole.log() ---> [1,2,3,5].
  2. second cosole.log() ----> [3,5,1,2]
Andre Nevares
  • 711
  • 6
  • 21
bilalo
  • 129
  • 1
  • 1
  • 7
  • 1
    Because `sort()` mutates the initial array so, by the time you expanding it in the console it looks just the same as its sorted version. – Yevhen Horbunkov Jun 09 '20 at 22:11
  • 1
    You're logging the same array, which was mutated. If it works with number primitives, then the console must be serializing it for you on each log. You'll probably get different results in different consoles. –  Jun 09 '20 at 22:12
  • `console.log(cardArray.slice(0));` – Taplar Jun 09 '20 at 22:15
  • You may log stringified version of arrays (use `console.log(JSON.stringify(cardArray))`) to see the difference. And by, the way, using `sort()` for array shuffling is a poor choice as your output is not so random (it returns your array unshiffled after couple of iterations). If you need something truly random, I may suggest [this](https://stackoverflow.com/a/56756447/11299053) – Yevhen Horbunkov Jun 09 '20 at 22:15
  • `let cardArray = [{ a: 1 }, { a: 2 }, { a: 3 }, { a: 5 }] //first console.log console.log(cardArray); cardArray = cardArray.sort((a, b) => 0.5 - Math.random()); //seconde console.log console.log(cardArray); ` this worked for me – halilcakar Jun 09 '20 at 22:16

0 Answers0