如何使用所有项目的新索引位置重新排列对象数组?

我有一个对象数组,我想以随机方式随机播放此数组。但是数组中的项目不能处于其原始位置。

for example this array: [{ id: 1 }, { x: 2 }, { i: 's' }]

can be: [{ i: 's' }, { id: 1 }, { x: 2 }, ]

but can't be: [{ x: 2 }, { id: 1 }, { i: 's' }] - cause the third item still in the index like before.

I try to do it using knuth-shuffle, but how to fix that code so it work so keep the original item position in the new array?

function shuffle(array) {
  let 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;
}
console.clear();

const items = [{ id: 1 },{ id: 2 }, { id: 3 }, { id: 4 }];

console.log(shuffle(items));
console.log(shuffle(items));
评论