简体   繁体   中英

I need to know how to iterate through an array without repeating

I want to randomly iterate an array runs while randomly selecting a mainSamplers and a secondarySamplers . The below code works but will repeat runs and I need to keep running it over and over.

 // program to get a random samplestrong text function getRandomItem(arr) { // get random index value const randomIndex = Math.floor(Math.random() * arr.length); // get random item const item = arr[randomIndex]; return item; } let runs = ["W1", "W2/W3", "W4/W6", "W5", "W7/W8", "E1/E2", "E3/E4", "E5/RB", "SA/SB", "LT", "LR1", "LR2", "LR3", "LR4", "LR5", "LR6", "LR7", "LR8", "Mullet Creek"]; let mainSamplers = ["RAB", "CJ", "AMR", "ND", "RB", "ED", "SD", "MEF"]; let secondarySamplers = ["KD", "SA", "AF", "JT", "EV"]; //1st sample set const result1 = getRandomItem(runs) + " " + getRandomItem(mainSamplers) + " " + getRandomItem(secondarySamplers); console.log("Run" + " " + "Samplers"); console.log(result1); // need to run this as many times as there are runs and not repeat the runs

You can delete each random element from run.

 // program to get a random samplestrong text function getRandomItem(arr) { // get random index value const randomIndex = Math.floor(Math.random() * arr.length); // get random item const item = arr[randomIndex]; return item; } let runs = ["W1", "W2/W3", "W4/W6", "W5", "W7/W8", "E1/E2", "E3/E4", "E5/RB", "SA/SB", "LT", "LR1", "LR2", "LR3", "LR4", "LR5", "LR6", "LR7", "LR8", "Mullet Creek" ]; let mainSamplers = ["RAB", "CJ", "AMR", "ND", "RB", "ED", "SD", "MEF"]; let secondarySamplers = ["KD", "SA", "AF", "JT", "EV"]; console.log("Run" + " " + "Samplers"); while (runs.length) { //1st sample set let val = getRandomItem(runs); const result1 = val + " " + getRandomItem(mainSamplers) + " " + getRandomItem(secondarySamplers); console.log(result1); runs.splice(runs.indexOf(val), 1); }

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