The code below works for a normal array but not with an array with object does anybody knows how to do this?
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
let temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
const result = shuffle(array);
console.log(JSON.stringify(result));
Shuffle Array using Random Class We can iterate through the array elements in a for loop. Then, we use the Random class to generate a random index number. Then swap the current index element with the randomly generated index element. At the end of the for loop, we will have a randomly shuffled array.
A JavaScript array elements can be shuffled by using the sort() method. The JavaScript Array sort() method is used to sort the elements of an array. The method accepts a comparison function and performs a sort based on the value returned by that function.
The first and simplest way to shuffle an array in JavaScript is to provide a custom function to a . sort() . const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const shuffledArray = array. sort((a, b) => 0.5 - Math.
Sorting array of objectsArrays of objects can be sorted by comparing the value of one of their properties.
Try sorting like this snippet:
console.log( [
{ some: 1 },
{ some: 2 },
{ some: 3 },
{ some: 4 },
{ some: 5 },
{ some: 6 },
{ some: 7 },
]
.sort( () => Math.random() - 0.5) );
In reponse to Martin Omanders comment: here's a shuffle method according to the Fisher-Yates algorithm
const result = document.querySelector("pre");
for (let i=0; i<20; i+=1) {
result.textContent +=
JSON.stringify(shuffleFisherYates([0,1,2,3,4,5,6,7,8,9])) + '\n';
}
function shuffleFisherYates(array) {
let i = array.length;
while (i--) {
const ri = Math.floor(Math.random() * i);
[array[i], array[ri]] = [array[ri], array[i]];
}
return array;
}
<pre></pre>
Which may be condensed to a one liner (note: this one liner will not compile in the Google Closure Compiler with level advanced):
const shuffle = array =>
[...Array(array.length)]
.map((el, i) => Math.floor(Math.random() * i))
.reduce( (a, rv, i) => ([a[i], a[rv]] = [a[rv], a[i]]) && a, array);
const result = document.querySelector("pre");
for (let i=0; i<100; i+=1)
result.textContent +=
JSON.stringify(shuffle([0,1,2,3,4,5,6,7,8,9])) + '\n';
<pre></pre>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With