gpt4 book ai didi

javascript - 如何洗牌除了固定位置的数组

转载 作者:行者123 更新时间:2023-12-05 02:25:46 25 4
gpt4 key购买 nike

有一个由轨道和歌曲组成的播放列表:

var arr = [         
{'title': 'jingle fixed'},
{'title': track 0},
{'title': track 1},
{'title': 'jingle fixed'},
{'title': track 2},
{'title': 'jingle fixed'},
{'title': track 3},
{'title': track 4},
{'title': track 5}
];

function shuffle(playList) {
let currentIndex = playList.length, randomIndex;

while (currentIndex != 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;

// How to except by playList.title?
[playList[currentIndex], playList[randomIndex]] = [playList[randomIndex], playList[currentIndex]];
}

return playList;
}

我只需要随机化(随机播放)轨道,并将歌曲留在原位。

预期的结果:

[           
{'title': 'jingle fixed'},
{'title': track 4},
{'title': track 1},
{'title': 'jingle fixed'},
{'title': track 5},
{'title': 'jingle fixed'},
{'title': track 3},
{'title': track 0},
{'title': track 1}
];

最佳答案

我确信有人可以找到更漂亮的解决方案,因为我认为这具有相当高的算法复杂性(复制一个数组,对其进行过滤,对其进行排序并重新创建一个映射第一个数组的数组......),但它有效。

const tracks = [{
title: 'jingle fixed'
},
{
title: "track 4"
},
{
title: "track 1"
},
{
title: 'jingle fixed'
},
{
title: "track 5"
},
{
title: 'jingle fixed'
},
{
title: " track 3"
},
{
title: "track 0"
},
{
title: "track 1"
}
];

const shuff_tracks = tracks.filter(t => t.title !== "jingle fixed");
shuff_tracks.sort(() => Math.floor(Math.random() * 10) % 2 === 0 ? 1 : -1);

let tr_i = -1;

const out = tracks.map(t => {
if (t.title === "jingle fixed") return t;
return shuff_tracks[++tr_i];
});

console.log(out)

关于javascript - 如何洗牌除了固定位置的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74317298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com