Randomize Array values in place with sort() method in JavaScript

Randomize Array values in place with sort() method in JavaScript

Use the sort method in JavaScript, notice the difference in values using a positive one and a negative one value in the return of the anonymous function within the sort parameters.  If you use Math random to return randomly a negative or positive value this will randomize the array items in place using the sort method.

<!DOCTYPE html>
<html>
<head>
   <title>JavaScript</title>
</head>
<body>
   <div class="output">
       <div class="box2">Laurence Svekis</div>
   </div>
   <script src="app2.js"></script>
</body>
</html>

const arr = ['pineapple','apple','banana','pear','cherry'];
const box2 = document.querySelector('.box2');
 
box2.addEventListener('click',makeArray);
 
console.log(arr);
 
function makeArray(){
   console.log(arr);
   arr.sort(()=> 0.5 - Math.random());
   console.log(arr);
   outputArray(arr);
}
 
function outputArray(a){
   box2.innerHTML = '';
   a.forEach((ele,index) => {
       console.log(ele);
       const div = document.createElement('div');
       div.textContent = `${index} ${ele}`;
       box2.append(div);
   })
}