假设我有两个数组:
let arr1 = [1,2,3,4,5] ;
let arr2 = ['a' , 'b', 'c'] ;
我想在 arr1 中随机插入 arr2 的元素。 arr2 的顺序并不重要,但 arr1 的顺序很重要。目标是得到这样的结果:
let mergedArray = [1 , 2, 'b', 3 , 'c',4, 'a',5] ;
我怎样才能做到这一点?
最佳答案
使用我的回答 here 中的函数,我们可以在两个数组上使用随机播放函数,我们将其与 concat
合并:
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;
}
let arr1 = [1, 2, 3, 4, 5];
let arr2 = ["a", "b", "c"];
let mergedArray = shuffle(arr1.concat(arr2));
console.log(mergedArray);
关于javascript - Node .js |将一个数组中的元素插入到另一个数组中的随机位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54284851/