How to shuffle an array of objects in javascript?

后端 未结 3 509
忘掉有多难
忘掉有多难 2021-01-05 12:45

The code below works for a normal array but not with an array with object does anybody knows how to do this?

3条回答
  •  -上瘾入骨i
    2021-01-05 13:10

    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

    for (let i=0; i<20; i+=1) {
      console.log(JSON.stringify(shuffleFisherYates([0,1,2,3,4,5,6,7,8,9])));
    }
    
    function shuffleFisherYates(array) {
      let i = array.length;
      while (i--) {
        const ri = Math.floor(Math.random() * (i + 1));
        [array[i], array[ri]] = [array[ri], array[i]];
      }
      return array;
    }

    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((...args) => Math.floor(Math.random() * (args[1] + 1)))
        .reduce( (a, rv, i) => ([a[i], a[rv]] = [a[rv], a[i]]) && a, array);
        
    for (let i=0; i<100; i+=1)
      console.log(JSON.stringify(shuffle([0,1,2,3,4,5,6,7,8,9])));

提交回复
热议问题