0

I want to generate random order of record data. Is there any clear and clever way with React hooks?

For example I have data:

let data = [
{user: user1, points: 5},
{user: user2, points: 6},
{user: user3, points: 8},
{user: user4, points: 1}
];

And with some random function I want to get some random order:

OUTPUT:

{user: user3, points: 8},
{user: user2, points: 6},
{user: user4, points: 1},
{user: user1, points: 5}

I don´t want to choose only one random element, but I want to get all elements from the data, but only in random order.

Ali
  • 103
  • 7
  • 1
    Does this answer your question? [How can I shuffle an array?](https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array) – Eldshe Mar 22 '21 at 20:59
  • Yes, Fisher-Yates algorithms works! :) Thank you very much – Ali Mar 23 '21 at 07:01

1 Answers1

0

The simplest way of doing that is using the sort method with random value:

data.sort(() => .5 - Math.random());
Bart Krakowski
  • 1,655
  • 2
  • 8
  • 25
  • Thank you for your answer. I tried this, but after the third click on the button (random draw), I got the same sorted data as first. But Fisher-Yates algorithm works. – Ali Mar 23 '21 at 07:03