如何随机排列对象数组

时间:2019-10-09 15:00:52

标签: javascript reactjs

我正在尝试使用shuffle的npm模块(https://www.npmjs.com/package/shuffle-array)来对对象数组进行洗牌-但是,我遇到了类似“ ypeError:Object(...)不是函数”的错误。

   let posts = [
   {
    postUrl: "https://www.linkedin.com/1",
    action: "Post",
    profileUrl: "https://www.linkedin.com/company/1",
    timestamp: "2019-10-09T09:40:05.356Z"
    },
    {
    postUrl: "https://www.linkedin.com/2",
    action: "Post",
    profileUrl: "https://www.linkedin.com/company/2",
    timestamp: "2019-10-09T09:40:05.356Z"
    },
    {
    postUrl: "https://www.linkedin.com/3",
    action: "Post",
    profileUrl: "https://www.linkedin.com/company/3",
    timestamp: "2019-10-09T09:40:05.356Z"
    },
]

posts = shuffle(posts);

可以看到我要去哪里了吗?或还有什么其他方法可以使这些对象随机播放?

3 个答案:

答案 0 :(得分:1)

对于大多数用途而言,实现此目的的最佳方法是使用Fisher Yates / Knuth混洗,因为我敢肯定会有其他人链接到它。本文对此进行了讨论:

How to randomize (shuffle) a JavaScript array?

随机化的肉归结为以下内容(也可以在前面的文章中找到!):

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

// Used like so
var arr = [2, 11, 37, 42];
arr = shuffle(arr);
console.log(arr);

希望这对您有所帮助!

答案 1 :(得分:0)

您可以使用数学函数random()来读取和分配数组中的索引。例如:

let thisarray = ["Hi","Hope","This","Helps!"];

var thisarrayprime = [];

for (let i = 0; i < thisarray.length; i++) {


   var newarray = Math.floor(Math.random() * thisarray.length);

   thisarrayprime[new] = thisarray[i];

   thisarray.splice((i-1), 1);

}

希望这会有所帮助!

答案 2 :(得分:0)

我试图在线运行您的代码。一切正常。
代码写在这里https://repl.it/repls/ClosedUnevenDevelopments
我认为您的项目设置存在一些问题。看一下这个线程https://github.com/facebook/react/issues/14484