I have a list of 10 items. I want to show only 3 random elements from the list: ONE element between 1 and 5.......TWO elements between 6 and 10. who can help me in this? thank you very much!
my code now shows all the elements together...
I would like to show something like:
3.
7.
9.
(only 3 elements)
var list = document.getElementById("items"),
newlist = document.getElementById("shuffle");
function shuffle(items)
{
var cached = items.slice(0), temp, i = cached.length, rand;
while(--i)
{
rand = Math.floor(i * Math.random());
temp = cached[rand];
cached[rand] = cached[i];
cached[i] = temp;
}
return cached;
}
function shuffleNodes()
{
var nodes = list.children, i = 0;
nodes = Array.prototype.slice.call(nodes);
nodes = shuffle(nodes);
while(i < nodes.length)
{
list.appendChild(nodes[i]);
i;
}
}
window.onload = shuffleNodes;
<form id="something">
<div >
<dl id="items">
<dd>1. item.<br></dd>
<dd>2. item.<br></dd>
<dd>3. item.<br></dd>
<dd>4. item.<br></dd>
<dd>5. item.<br></dd>
<dd>6. item.<br></dd>
<dd>7. item.<br></dd>
<dd>8. item.<br></dd>
<dd>9. item.<br></dd>
<dd>10. item.<br></dd>
</dl>
</div>
</form>
CodePudding user response:
I think it is better to work with arrays in this case. You can create an items array and then another array to store all the random indexes. Finally use the random indexes RI to get the random items to insert into the HTML.
function execute(){
const list = document.getElementById("list")
const rand = () => {return Math.random()}
// Destructure the list childrens inside an array
const items = [...list.children];
// Erase the list
list.innerHTML = ''
// `RI` stands for random index
const RI = [
Math.round(rand() * 4), // Rand between 0 and 4
5 Math.round(rand()), // Rand between 5 and 6
7 Math.round(rand() * 2) // Rand between 7 and 9
]
// Append html list items
list.append(items[RI[0]])
list.append(items[RI[1]])
list.append(items[RI[2]])
// Remove the button
document.getElementById('btn').remove()
}
<button id='btn' onClick='execute()'>Get random list</button>
<ul id='list'>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
<li>item 5</li>
<li>item 6</li>
<li>item 7</li>
<li>item 8</li>
<li>item 9</li>
<li>item 10</li>
</ul>
CodePudding user response:
First, you need a function that will generate a random number between 2 random numbers, this answer was taken here.
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min 1) min)
}
and then what you need to do on your shuffleNodes is (comments on code):
function shuffleNodes()
{
var nodes = list.children;
// generate 3 random numbers first based on what you want, this will be your indexes
var first = randomIntFromInterval(1, 5);
var second = randomIntFromInterval(6, 10);
var third = randomIntFromInterval(6, 10);
[first, second, third].map((val) => {
// add that index on the node so you can select it
var randomList = nodes[val];
// do your logic here
list.appendChild(randomList);
})
}
