JavaScript Function to shuffle and display random all elements from Array click on button
<h1>Array Elements</h1>
<script>
const myArray = ['apple', 'banana', 'orange'];
function displayArrayElements(array) {
// Shuffle the array
const shuffledArray = shuffle(array);
// Create an array of li elements
const liElements = shuffledArray.map(function(element) {
// Create an li element
const li = document.createElement('li');
// Set the text content of the li element to the current element
li.textContent = element;
return li;
});
// Get the element to append the array elements to
const element = document.getElementById('array-elements');
// Clear the element
element.innerHTML = '';
// Append the li elements to the DOM
liElements.forEach(function(li) {
element.appendChild(li);
});
}
// Shuffle function
function shuffle(array) {
let currentIndex = array.length;
let temporaryValue;
let randomIndex;
// While there remain elements to shuffle...
while (currentIndex !== 0) {
// 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;
}
</script>
<ul id="array-elements"></ul>
<button onclick="displayArrayElements(myArray)">
Display Array Elements
</button>