Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shuffle an array of objects in javascript?

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));
like image 721
Arne Avatar asked Mar 29 '18 11:03

Arne


People also ask

How do you shuffle an object array?

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.

How can I shuffle an array JavaScript?

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.

How do you shuffle an object in JavaScript?

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.

Can you sort an array of objects in JavaScript?

Sorting array of objectsArrays of objects can be sorted by comparing the value of one of their properties.


1 Answers

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>
like image 87
KooiInc Avatar answered Oct 14 '22 20:10

KooiInc