简体   繁体   中英

node.js | Inserting elements from one array into random locations within another array

Lets say I have two arrays:

let arr1 = [1,2,3,4,5] ;
let arr2 = ['a' , 'b', 'c'] ;

I want to insert elements of arr2 inside arr1 randomly. the order of arr2 is not important but order of arr1 is. The goal is to have this result:

let mergedArray = [1 , 2, 'b', 3 , 'c',4, 'a',5] ;

How can I achieve this ?

Using the function from my answer here , we can use a shuffle function on the two arrays, which we merge with 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); 

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)

My simple way: Mixing arr2 then insert each item of arr2 to arr1 randomize

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);
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);

This will be help you

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM