让我说我有两个数组:
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] ;
我该如何实现?
答案 0 :(得分:2)
使用答案here中的函数,我们可以在两个数组上使用shuffle函数,并与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);
答案 1 :(得分:1)
let arr1 = [1,2,3,4,5] ;
let arr2 = ['a' , 'b', 'c'] ;
var len1 = arr1.length
var mergedArr = arr1.slice()
for(var i = 0; i< arr2.length; i++){
var rand = Math.floor(Math.random() * (len1 - 0)) + 1
mergedArr.splice(rand, 0, arr2[i])
}
console.log(mergedArr)
答案 2 :(得分:1)
我的简单方法:混合arr2,然后将arr2的每个项随机插入arr1
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
function shuffle(arr1, arr2) {
// Randomize arr2 element order in-place.
shuffleArray(arr2);
arr2.forEach(item => {
// Randomize index of arr1
let i = getRandomInt(0, arr1.length);
// Insert item to arr1
arr1.splice(i, 0, item);
});
return arr1;
}
let arr1 = [1, 2, 3, 4, 5];
let arr2 = ["a", "b", "c"];
let result = shuffle(arr1.concat(arr2));
console.log(result);
答案 3 :(得分:1)
var one=[1,2,3,4];
var two=['a','b','c'];
var three=one.concat(two);
var four=[];
var test=three.length;
for(i=0;i<test;i++){
let j=Math.floor((Math.random() * three.length));
four.splice(j, 0,three[i]);
}
console.log(four);
答案 4 :(得分:0)
这将为您提供帮助
let arr1 = [1,2,3,4,5] ;
let arr2 = ['a' , 'b', 'c'] ;
arr2.map((values,i)=>{
var rand = Math.floor(Math.random() * (arr1.length)) + 1;
arr1.splice(rand, 0,values);
})
console.log(arr1)